由于单一定义规则,在 C 或 C++ 中不允许对全局变量进行多重定义。但是,在 C++ 中,一个 const 全局变量可以在多个编译单元中定义而不会出错。这与 C 中的不同。
为什么 C++ 允许,而 C 不允许?与 C 相比,为什么 C++ 中 const 全局变量的用法和行为与非 const 全局变量有这种不同? C++ 和 C 在 const 方面发生了什么?
例如,这在 C++ 中是允许的,但在 C 中是错误的:
// Foo.cpp
const int Foo = 99;
// Main.cpp
const int Foo = 99;
int main()
{
cout << Foo << endl;
return 0;
}
这对 C 来说很好,但对 C++ 来说是错误的:
// Foo.cpp
const int Foo = 99;
// Main.cpp
extern const int Foo;
int main()
{
cout << Foo << endl;
return 0;
}
最佳答案
// Foo.cpp
const int Foo = 99;
// Main.cpp
const int Foo = 99;
命名空间范围内的 const
变量具有 internal 链接。所以它们基本上是两个不同的变量。没有重新定义。
来自@David 的评论,3.5/3 [basic.link]:
A name having namespace scope (3.3.5) has internal linkage if it is the name of
— an object, reference, function or function template that is explicitly declared static or,
— an object or reference that is explicitly declared const and neither explicitly declared extern nor previously declared to have external linkage; or
— a data member of an anonymous union.
在第二种情况下,你应该这样做(正确的方法):
//Foo.h
extern const int Foo; //use extern here to make it have external linkage!
// Foo.cpp
#include "Foo.h"
const int Foo = 99; //actual definition goes here
// Main.cpp
#include "Foo.h"
int main()
{
cout << Foo << endl;
}
关于c++ - 为什么在 C++ 中允许对 const 全局变量进行多重定义,而在 C 中却不允许?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6173872/