C++ 局部范围内的多重声明

标签 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 行。

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

最佳答案

extern 声明声明具有外部链接 的内容(意味着该定义预计会出现在某个编译单元(可能是当前编译单元)的文件范围内。局部变量不能有外部链接,所以编译器会提示你试图做一些自相矛盾的事情。

关于C++ 局部范围内的多重声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5185833/

相关文章:

c++ - 为什么必须复制 libstdc++-6.dll 才能运行我的 C++ 程序?

C++:如何使用尚未定义的类型?

c++ - std::normal_distribution 的类型取决于模板

java - Java Integers默认为int

scala - scala 'match' 编译规则的误解

C++类重定义错误求助

JavaScript 初始化函数

java包声明

c++ - 使用 std::bind 删除参数

c++ - 在虚函数上使用 enable_if