c++ - c++ 允许提升还是特定于编译器?即使

标签 c++ namespaces declaration extern linkage

因此,我正在查看各种问题以准备明天的面试,并遇到了 extern 关键字,我知道 extern 关键字指定为属于另一个程序的变量分配内存(不知道在哪里使用)但真正的疑问是,

#include<iostream>
using std::cout;


int main()
{
    extern int a;
    cout<<a;
    
    return 0;
}

int a=20;


output:
 20
我想知道这是如何工作的?即使提升在 c++ 中工作,我也知道一些 JS 提升,即使首先完成 a 作为 int a 的声明,然后完成分配,输出也应该是一个值,一个垃圾值......

最佳答案

对于这个块范围声明

extern int a;
编译器搜索名​​称 a 的先前声明在全局命名空间中确定它是否具有外部或内部链接。如果编译器没有找到之前的声明,它会认为变量 a指在具有外部链接的全局命名空间中定义的变量。
并且确实在全局命名空间中有一个变量的定义
int a=20;
所以这两个声明引用了全局命名空间中定义的同一个对象。
来自 C++ 17 标准(6.5 程序和链接)

2 A name is said to have linkage when it might denote the same object, reference, function, type, template, namespace or value as a name introduced by a declaration in another scope:



6 The name of a function declared in block scope and the name of a variable declared by a block scope extern declaration have linkage. If there is a visible declaration of an entity with linkage having the same name and type, ignoring entities declared outside the innermost enclosing namespace scope, the block scope declaration declares that same entity and receives the linkage of the previous declaration. If there is more than one such matching entity, the program is ill-formed. Otherwise, if no matching entity is found, the block scope entity receives external linkage. If, within a translation unit, the same entity is declared with both internal and external linkage, the program is ill-formed.


这是一个在块作用域中的声明,带有存储类说明符 extern不定义新对象。它指的是在封闭命名空间中定义的具有内部或外部链接的同名对象。

关于c++ - c++ 允许提升还是特定于编译器?即使,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69433298/

相关文章:

python - 如何在不移动 namespace 的情况下使用 Python 的 ElementTree 解析和编写 XML?

python - 无法安装两个使用相同命名空间的包

c++ - 使用 C++ 将 IP 地址 append 到 char*

c++ - 创建动态数组静态成员(计数器)时增加

visual-studio-2008 - 从 MVC 项目访问类库?

c++ 'static int' 不能跨多个文件工作吗?

c - 简单的 C 程序产生空白输出 - 没有错误

c++ - main.cpp :22:34: error: ‘xxxxxxx’ was not declared in this > scope

c++ - 包含特定文件时可以抑制所有警告吗?

c++ - 关于用括号括起来的声明类型是什么的问题