If an object or a function does not need to be visible outside the current scope, it should be hidden by being declared as static
. This creates more modular code and limits pollution of the global name space. If the compilation unit implements a data abstraction, it may also expose invocations of private functions from outside the abstraction.
Wiki Markup |
---|
Section 6.2.2 of C99 \[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] states that |
...
If the declaration of an identifier for an object has file scope and no storage-class specifier, its linkage is external.
If an object, such as a function, does not need to be visible outside the current scope, it should be hidden by being declared as static
. This helps create more modular code and may expose hidden assumptions about abstraction.
Non-Compliant Code Example
...
Code Block | ||
---|---|---|
| ||
enum { MAX = 100 }; int helper(int i) { /* perform some computation based on i */ } int main(void) { intsize_t i; int out[MAX]; for (i = 0; i < MAX; i++) { out[i] = helper(i); } /* ... */ return 0; } |
Compliant Solution
This compliant solution declares helper()
to have internal linkage, thereby preventing objects from other scopes from using it.
Code Block | ||
---|---|---|
| ||
enum {MAX = 100}; static int helper(int i) { /* perform some computation based on i */ } int main(void) { intsize_t i; int out[MAX]; for (i = 0; i < MAX; i++) { out[i] = helper(i); } /* ... */ return 0; } |
Risk Assessment
Allowing too many objects to have external linkage can use up descriptive identifiers, leading to more complicated identifiers, violations of abstraction models, and possible name conflicts with libraries.
...