linux - 为什么 linux 内核中的全局变量是静态的?

标签 linux static linux-kernel

我正在阅读 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/

相关文章:

linux - 为什么找到需要 "{}\"?

c - 将输出重定向到文件时 printf() 和 system() 的结果顺序错误

java - 接口(interface)中的静态类和非静态类有什么区别?

c# - 为什么 Visual Studio 不警告静态字符串的循环初始化?

c - _do_fork() 如何返回两个不同的 PID(一个用于父进程,一个用于子进程)

linux - 尽管设置了 MODULE_LICENSE,但仍收到消息 "module license ' 未指定的“污点内核”

c++ - Qt Creator 4.0.2 和 Beaglebone Black 与 Ubuntu 16.04.3

java - 如何解决 "static method ___ should be accessed in a static way"警告

c - 获取猫 :/dev/mydevice1: Invalid argument as output when trying to communicate in driver

android - 在 c 文件名的开头和结尾之后使用双下划线 ( __ ) 的目的是什么?