在 C++ 中的给定相同范围内声明相同的变量名称

Declaring the same variables name within a given same scope in C++

我正在尝试理解 C++ 中的 存储 class 说明符 。我有两个案例。

此处,在给定的相同范围内,声明相同的变量名称。

案例一:

#include <iostream>

static int i; 
extern int i; 

int main() {
    std::cout<<i<<std::endl;
    return 0;
}

输出:

0

案例二:

#include <iostream>

extern int i; 
static int i; 

int main() {
    std::cout<<i<<std::endl;
    return 0;
}

获取错误:

prog.cpp:4:12: error: 'i' was declared 'extern' and later 'static' [-fpermissive]
 static int i; 
            ^
prog.cpp:3:12: note: previous declaration of 'i'
 extern int i;

为什么第一个案例工作正常而第二个案例给出错误?

extern 有点特殊,因为标有它的声明会查找同一实体的先前声明,如果找到,则使用先前的链接。只有当找不到时,它才会声明一个具有外部链接的新实体。

static,另一方面,无条件声明其具有内部链接的实体。

这意味着这段代码只是声明和定义了 i 内部链接。第二个声明找到第一个并重用它的链接。

static int i;
extern int i;

而此代码声明变量具有外部链接,然后声明并定义它具有内部链接,这是一个错误。

extern int i;
static int i;

这种行为的原因很难追踪,但很可能可以追溯到 C 的前标准时代。

在 C++ 中,此行为由 [basic.link]、最新草案 N4687 中的 6.5/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.