Section 6.2.2 of C99 \[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] states that |
If the declaration of a file scope identifier for an object or a function contains the storage-class specifier
static, the identifier has internal linkage.
and
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.
This non-compliant code example includes a helper() function that is implicitly declared to have external linkage.
enum {MAX = 100};
int helper(int i) {
/* perform some computation based on i */
}
int main(void) {
int i;
int out[MAX];
for (i = 0; i < MAX; i++) {
out[i] = helper(i);
}
/* ... */
return 0;
}
|
This compliant solution declares helper() to have internal linkage, thereby preventing objects from other scopes from using it.
enum {MAX = 100};
static int helper(int i) {
/* perform some computation based on i */
}
int main(void) {
int i;
int out[MAX];
for (i = 0; i < MAX; i++) {
out[i] = helper(i);
}
/* ... */
return 0;
}
|
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.
Recommendation |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
|---|---|---|---|---|---|
DCL15-A |
low |
unlikely |
low |
P3 |
L3 |
Splint Version 3.1.1 can detect violations of this rule.
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
\[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] Section 6.2.2, "Linkages of identifiers" |
DCL14-A. Do not make assumptions about the order of global variable initialization across translation units 02. Declarations and Initialization (DCL)