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

发布于 2024-10-19 22:33:31 字数 753 浏览 5 评论 0原文

据我所知,在 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 行。

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

As far as I know, in C++ one can declare the same name multiple times, as far as it has the same type in all these declarations. To declare an object of type int, but NOT define it, the extern keyword is used. So the following should be correct and compile without errors:

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.

But once I moved this to the inside of a function, the compiler (GCC 4.3.4) complains that I am redeclaring x and that it's illegal. The error message is the following:

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

where int x = 5; is in line 9, and extern int x is in line 8.

My question is:
If multiple declarations are not supposed to be errors, then WHY is it an error in this particular case?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

九命猫 2024-10-26 22:33:31

extern 声明声明某些内容具有外部链接(意味着该定义预计出现在某个编译单元(可能是当前编译单元)的文件范围内)。局部变量不能具有外部链接,因此编译器会抱怨您正在尝试做一些矛盾的事情。

An extern declaration declares something to have external linkage (meaning the definition is expected to appear at file scope in some compilation unit, possibly the current one). Local variables cannot have external linkage, so the compiler complains that you're trying to do something contradictory.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文