2017-10-16 206 views
3

我想了解C++中的存储类说明符。我有两个例子。在C++中给定的相同范围内声明相同的变量名称

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

情况1:

#include <iostream> 

static int i; 
extern int i; 

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

输出:

0 

情况2:

#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; 

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

+1

看起来更像是C++ - 你确定你有正确的标签吗? –

回答

13

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.

相关问题