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 creates more modular code and limits pollution of the global name space.
Section 6.2.2 of C99 of the C standard [ISO/IEC 9899:19992011] 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.
...
| 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);
}
/* ... */
}
|
...
| 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);
}
/* ... */
}
|
...
Tool | Version | Checker | Description | |||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Section | Splint |
|
| section | ||||||||
| 27 D | | Section | Fully Implementedimplemented |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...
CERT C++ Secure Coding Standard: DCL15-CPP. Declare file-scope objects or functions that do not need external linkage in an unnamed namespace
ISO/IEC 9899:19992011 Section 6.2.2, "Linkages of identifiers"
...