C 中 "extern" 变量的生命周期?

Lifetime of "extern" variable in C?

如果声明为 extern int p;

,变量 p 的生命周期是多少

它是静态的、动态的、自动的还是因为没有链接而没有生命周期?

谈论由 extern 声明引入的名称的生命周期没有多大意义 - 存储持续时间是 属性 个 对象 ,不是名字.

另一方面,extern变量声明只能引用全局变量,它具有静态存储持续时间。

or it has no lifetime because there is no linkage?

关键字extern表示一个变量只被声明,没有分配存储空间[1].

关键字extern与变量的生命周期无关。也就是说,变量的生命周期 time/scope 仅取决于它在代码中出现的确切位置。

备注

[1] 当 extern

这样的赋值一起使用时
extern int i=5; 

关键字extern被忽略,通常的作用域规则适用于变量

[2] 请检查我的其他 关于这个。


有趣:正如 Stephen Prata 在他的《C++ Primer Plus》一书中所说,关键字 extern 表示 "Use the variable by this name previously defined externally"

C11 草案第 6.2.4 节说

An object whose identifier is declared without the storage-class specifier _Thread_local, and either 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 and its stored value is initialized only once, prior to program startup.

程序的生命周期。在加载时或程序启动时初始化一次。默认初始值为0。不能在块内初始化。