我经历了以下两个问题:
C 和 C++ 中的静态和外部全局变量一个>
C 中的全局变量是否是静态的?
两个问题都以不同的方式说明了这两件事.
问题 1 的答案:
<块引用>全局变量在 C 和 C++ 上默认不是 extern 或 static.
问题 2 的答案:
<块引用>如果不指定存储类(即extern或static关键字),则默认全局变量有外部链接
我需要知道以下几点:
extern
(或)是否等同于通过指定extern
存储类来声明变量?static
(或)是否等同于通过指定static
存储类来声明变量?C
或 C++
有什么区别吗?任何人都可以澄清一下吗?全局变量是否在链接中默认为
extern
(或)相当于通过指定extern
存储类来声明变量?
在任何块之外声明的变量的默认存储持续时间、作用域和链接,在最外层,有static
存储持续时间、file作用域和external
联动.C11 标准说:
[...] 如果声明标识符的声明符或类型说明符出现在任何块或参数列表之外,则标识符具有文件范围,它终止在翻译单元的末尾.[...]
[...] 如果对象的标识符声明具有文件范围且没有存储类说明符,则其链接是external
.
一个对象,其标识符声明时没有存储类说明符_Thread_local
,与 external 或 internal 链接或存储类说明符 static
,具有 静态存储时长.
所以,如果 x
是全局的
int x;
那么它的存储时长、作用域和链接等价于
中的x
extern int x;
<块引用>
全局变量在范围内是否默认为static
(或)相当于通过指定static
存储类来声明变量?
没有.正如我上面所说,它的持续时间是 static
并且它具有 file 范围.
如果有任何 c 或 c++ 差异,请澄清?
没有区别.两种语言的规则相同.
I have gone through following two questions:
static and extern global variables in C and C++
global variable in C are static or not?
Both questions says the two things in different way.
Question 1's Answer:
Global variables are not extern nor static by default on C and C++.
Question 2's Answer:
If you do not specify a storage class (that is, the extern or static keywords), then by default global variables have external linkage
I need to know the following:
extern
by default in linkage (or) is it equivalent to declaring variables by specifying extern
storage class?static
by default in scope (or) is it equivalent to declaring variables by specifying static
storage class?C
or C++
? Can anyone please clarify?
is global variables are
extern
by default in linkage (or) it is equivalent to declaring variable by specifyingextern
storage class?
The default storage duration, scope and linkage of variables declared outside any block, at the outer most level, have static
storage duration, file scope and external
linkage. C11 standard says that:
[...] If the declarator or type specifier that declares the identifier appears outside of any block or list of parameters, the identifier has file scope, which terminates at the end of the translation unit. [...]
[...] If the declaration of an identifier for an object has file scope and no storage-class specifier, its linkage is
external
.
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 specifierstatic
, has static storage duration.
So, if x
is global
int x;
then its storage duration, scope and linkage is equivalent to x
in
extern int x;
is global variables are
static
by default in scope (or) it is equivalent to declaring variable by specifyingstatic
storage class?
No. As I stated above that its duration is static
and it has file scope.
If there is any c or c++ difference please clarify?
No difference. Rule is same in both languages.
这篇关于默认情况下全局变量是 extern 还是等同于在 global 中使用 extern 声明变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!