我正在阅读 TLDP并注意到所有全局变量和函数都声明为静态的。进一步阅读后,我了解到将变量声明为静态是为了减少命名空间污染。
根据 this所以发帖,
static functions are functions that are only visible to other functions in the same file (more precisely the same translation unit).
因此将函数声明为静态将减少 namespace 污染。但是,在变量的情况下,根据 TLDP :
When a Static variable is modified by a module, all other modules will see the new value.
它会增加命名空间污染。全局静态变量不是也对同一个翻译单元可见吗?如果是这样,上面引用的陈述怎么会是真的?我似乎错过了什么。
最佳答案
When a Static variable is modified by a module
我相信你误解了那句话。这可能有点令人困惑。它不是指 C static
关键字。它指的是 C 标准对“静态存储持续时间”的使用。引用C标准6.2.4节:
1 An object has a storage duration that determines its lifetime. There are three storage durations: static, automatic, and allocated.
....
3 An object whose identifier is declared with external or internal linkage, or with the storage-class specifier static has static storage duration. Its lifetime is the entire execution of the program
也就是说,“静态存储期”变量既包括全局变量,也包括用Cstatic
关键字声明的变量。在 TLDP 文章中,它指的是前者。
关于linux - 为什么 linux 内核中的全局变量是静态的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39861058/