If an a file-scope object or a function does not need to be visible outside of the current scopefile, it should be hidden by being declared as static
. This creates more modular code and limits pollution of the global name space.
...
If the declaration of an identifier for an object has file scope and no storage-class specifier, its linkage is external.
Noncompliant Code Example
This noncompliant code example includes a helper()
function that is implicitly declared to have external linkage.
Code Block | ||
---|---|---|
| ||
enum { MAX = 100 }; int helper(int i) { /* perform some computation based on i */ } int main(void) { size_t i; int out[MAX]; for (i = 0; i < MAX; i++) { out[i] = helper(i); } /* ... */ } |
Compliant Solution
This compliant solution declares helper()
to have internal linkage, thereby preventing external functions from using it.
Code Block | ||
---|---|---|
| ||
enum {MAX = 100}; static int helper(int i) { /* perform some computation based on i */ } int main(void) { size_t i; int out[MAX]; for (i = 0; i < MAX; i++) { out[i] = helper(i); } /* ... */ } |
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. If the compilation unit implements a data abstraction, it may also expose invocations of private functions from outside the abstraction.
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
DCL15-C | low | unlikely | low | P3 | L3 |
Automated Detection
Splint Version 3.1.1 can detect violations of this rule.
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Other Languages
This rule appears in the C++ Secure Coding Standard as DCL15-CPP. Declare objects that do not need external linkage with the storage-class specifier static.
References
Wiki Markup |
---|
\[[ISO/IEC 9899:1999|AA. C References#ISO/IEC 9899-1999]\] Section 6.2.2, "Linkages of identifiers" |
...