Rules:
1.8.a. The static keyword shall be used to declare all functions and variables that do not need to be visible outside of the module in which they are declared.
1.8.b. The const keyword shall be used whenever appropriate. Examples include:
i. To declare variables that should not be changed after initialization,
ii. To define call-by-reference function parameters that should not be modified (e.g., char const * param),
iii. To define fields in a struct or union that should not be modified (e.g., in a struct overlay for memory-mapped I/O peripheral registers), and
iv. As a strongly typed alternative to #define for numerical constants.
1.8.c. The volatile keyword shall be used whenever appropriate. Examples include:
i. To declare a global variable accessible (by current use or scope) by any interrupt service routine,
ii. To declare a global variable accessible (by current use or scope) by two or more threads,
iii. To declare a pointer to a memory-mapped I/O peripheral register set (e.g., timer_t volatile * const p_timer), and
iv. To declare a delay loop counter.
Example:
typedef struct
{
uint16_t count;
uint16_t max_count;
uint16_t const _unused; // read-only register
uint16_t control;
} timer_reg_t;
timer_reg_t volatile * const p_timer = (timer_reg_t *) HW_TIMER_ADDR;
Reasoning: C’s static keyword has several meanings. At the module-level, global variables and functions declared static are protected from external use. Heavy- handed use of static in this way thus decreases coupling between modules.
The const and volatile keywords are even more important. The upside of using const as much as possible is compiler-enforced protection from unintended writes to data that should be read-only. Proper use of volatile eliminates a whole class of difficult-to-detect bugs by preventing compiler optimizations that would eliminate requested reads or writes to variables or registers.4
Enforcement: These rules shall be enforced during code reviews.
Footnotes
[4] Anecdotal evidence suggests that programmers unfamiliar with the volatile keyword believe their compiler’s optimization feature is more broken than helpful and disable optimization. We believe that the vast majority of embedded systems contain bugs waiting to happen due to missing volatile keywords. Such bugs typically manifest themselves as “glitches” or only after changes are made to a “proven” code base.