全局变量的默认存储类别是什么?
在网上搜索时我发现,一些网站说它是静态
。但是,静态意味着内部链接,并且变量在文件范围之外不可用,即它不应对其他目标文件可用。但是,仍然可以使用 extern int i
等声明来访问其他文件。
而且,如果我明确提及全局变量static
,那么它在文件范围之外不可用。
那么,全局变量的正确默认存储类别是什么?
What is default storage class of a global variable?
While searching on web I found, some sites say it is static
. But, static means internal linkage and the variable can not be available outside the file scope i.e it should not be available to other object files. But, they still can be accessed to other files using declarations like extern int i
.
And, if I explicitly mention static
to global variable then it is not available outside the file scope.
Then, what is correct default storage class for the global variables?
发布评论
评论(2)
所谓的“全局”变量没有“默认存储类别”。当变量在命名空间范围内定义时,它始终具有静态存储持续时间。没有办法改变这一点,这就是为什么“默认”的想法在这里不适用。 (存储持续时间是它的正确名称。)
当您将关键字
static
应用于命名空间范围内定义的变量时,它不会影响其存储持续时间< /em> - 它已经是静态的并且仍然是静态的 - 但它会影响它链接。关键字static
将此类变量的链接从外部(默认)更改为内部。 链接是一个单独的概念,实际上与存储持续时间无关。There's no "default storage class" for what is commonly known as "global" variables. When a variable is defined in namespace scope it always has static storage duration. There's no way to change that, which is why the idea of something "default" is not applicable here. (And storage duration is what it is correctly called.)
When you apply the keyword
static
to a variable defined in namespace scope it does not affect its storage duration - it was static already and it remains static - but it affects it linkage. The keywordstatic
changes the linkage of such variable from external (default) to internal. Linkage is a separate concept, virtually unrelated to storage duration.默认存储持续时间是静态的,但默认链接是外部的。您并不是唯一一个觉得这有点令人困惑的人。 The C Book(始终是一个很好的参考)说:
引用这句话的部分,声明、定义和可访问性,有一个有用的表(8.1)。最后一行描述了您感兴趣的情况。正如它所指出的,没有存储类说明符的数据对象具有外部链接和静态持续时间。
The default storage duration is static, but default linkage is external. You're not the only one to find it a bit confusing. The C Book (always a good reference) says:
The section with that quote, Declarations, Definitions and Accessibility, has a helpful table (8.1). The last row describes the case you're interested in. As it notes, data objects with no storage class specifier have external linkage and static duration.