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

Sas*_*asQ 2 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.
Run Code Online (Sandbox Code Playgroud)

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

test.cc:9: error: declaration of 'int x'
test.cc:8: error: conflicts with previous declaration 'int x'
Run Code Online (Sandbox Code Playgroud)

int x = 5;第9行在哪里,extern int x在第8行.

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

Gre*_*ill 7

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