c++ - 默认情况下全局变量是extern还是相当于在全局中用extern声明变量?

标签 c++ c static global extern

我已经完成了以下两个问题:

static and extern global variables in C and C++

global variable in C are static or not?

这两个问题以不同的方式表达了两件事。

问题1的答案:

Global variables are not extern nor static by default on C and C++.

问题2的答案:

If you do not specify a storage class (that is, the extern or static keywords), then by default global variables have external linkage

我需要知道以下内容:

  1. 全局变量extern是否默认链接(或)是否等同于通过指定extern存储类来声明变量?
  2. 全局变量是否默认为 static 作用域(或者)是否等同于通过指定 static 存储类来声明变量?
  3. CC++ 有什么区别吗?谁能澄清一下?

最佳答案

is global variables are extern by default in linkage (or) it is equivalent to declaring variable by specifying extern storage class?

在任何 block 外声明的变量的默认存储持续时间、作用域和链接,在最外层,具有static 存储持续时间、file 作用域和external 链接。 C11 标准说:

6.2.1 标识符的范围(p4):

[...] 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. [...]

6.2.2 标识符的链接(p5):

[...] If the declaration of an identifier for an object has file scope and no storage-class specifier, its linkage is external.

6.2.4 对象的存储时长(p3):

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.

所以,如果 x 是全局的

int x;

那么它的存储时长、作用域和链接等同于

中的x
extern int x;   

is global variables are static by default in scope (or) it is equivalent to declaring variable by specifying static storage class?

没有。正如我上面所说,它的持续时间是 static 并且它有 file 范围。

If there is any c or c++ difference please clarify?

没有区别。两种语言的规则相同。

关于c++ - 默认情况下全局变量是extern还是相当于在全局中用extern声明变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39181204/

相关文章:

C++11 多播委托(delegate)实现

c++ - vector 排序只是用自定义比较器反转输入

c - 链表不打印

c++ - "static functions with block scope are illegal"错误取决于初始化样式?

java - 对Java中数据初始化的困惑

c++ - 使用 std::list 的编译器错误

c++ - 无法执行 Netbeans 创建的 .o 文件

flutter - 如何在 dart/flutter 中继承静态方法?

If Else 条件中的Continue 语句给出无限循环

php - zend 引擎返回对象引用