If a file-scope object or a function does not need to be visible outside of the file, it should be hidden by being declared as static. This practice creates more modular code and limits pollution of the global name space.
...
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);
}
/* ... */
}
|
...
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);
}
/* ... */
}
|
...
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Related Guidelines
| CERT C++ Secure Coding Standard | DCL15-CPP. Declare file-scope objects or functions that do not need external linkage in an unnamed namespace |
Bibliography
| ISO/IEC 9899:2011 | Section 6.2.2, "Linkages of Identifiers" |
...