C ++本地范围内的多个声明

时间:2011-03-03 19:57:03

标签: c++ compiler-errors declaration definition redeclaration

据我所知,在C ++中,只要在所有这些声明中具有相同的类型,就可以多次声明相同的名称。要声明int类型的对象,但不定义它,则使用extern关键字。所以以下内容应该是正确的并且编译没有错误:

extern int x;
extern int x; // OK, still declares the same object with the same type.
int x = 5;    // Definition (with initialization) and declaration in the same
              // time, because every definition is also a declaration.

但是一旦我将它移到函数内部,编译器(GCC 4.3.4)就会抱怨我正在重新声明x并且它是非法的。错误消息如下:

test.cc:9: error: declaration of 'int x'
test.cc:8: error: conflicts with previous declaration 'int x'

其中int x = 5;位于第9行,extern int x位于第8行。

我的问题是:
如果多个声明不应该是错误,那么为什么在这种特殊情况下它是错误的?

1 个答案:

答案 0 :(得分:7)

extern声明声明了具有外部链接的东西(意味着该定义应该出现在某些编译单元的文件范围内,可能是当前的编译单元)。局部变量不能有外部链接,因此编译器抱怨你试图做一些矛盾的事情。

相关问题