为什么一个const全局变量的多个定义在C ++和不是在C允许? [英] Why is multiple definition of a const global variable allowed in C++ and not in C?
问题描述
全局变量的多重定义不C或C ++允许由于在一个定义规则。然而,在C ++中一个const全局变量可以在多个编译单元,没有错误定义。这是不一样的在C
为什么C ++允许这个而C不?为什么一个const全球的使用和行为从非const全局++中这种方式使用C和C相比有什么不同?什么是用C ++和C就在幕后发生的事情为const?
例如这是允许在C ++中,但错在C:
// Foo.cpp中
const int的美孚= 99;// Main.cpp的
const int的美孚= 99;
诠释的main()
{
COUT<<美孚<< ENDL;
返回0;
}
这是罚款与C,但不对C ++:
// Foo.cpp中
const int的美孚= 99;// Main.cpp的
的extern const int的富;
诠释的main()
{
COUT<<美孚<< ENDL;
返回0;
}
// Foo.cpp中
const int的美孚= 99;// Main.cpp的
const int的美孚= 99;
在命名空间内常量
变量的内部的联动。所以,他们基本上两个不同的变量。有没有重新定义。
从@大卫的评论,3.5 / 3 [basic.link]:
一个有名字命名空间范围(3.3.5)
有内部链接如果它的名字
结果的
- 一个对象,引用,功能或
函数模板是明确
声明为static或结果
- 一个对象或
参考就是明确宣布
const和既没有明确声明
EXTERN也不previously声明为
外部链接;或结果
- 数据成员
一个匿名联合。
块引用>在第二种情况下,你应该这样做(正确的方法):
// foo.h中
的extern const int的富; //这里使用extern使其具有外部链接!// Foo.cpp中
的#includefoo.h中
const int的美孚= 99; //实际的定义放在这里// Main.cpp的
的#includefoo.h中
诠释的main()
{
COUT<<美孚<< ENDL;
}Multiple definition of a global variable is not allowed in C or C++ due to the One Definition Rule. However, in C++ a const global variable can be defined in multiple compilation units with no error. This is not the same as in C.
Why does C++ allow this while C does not? Why does the usage and behaviour of a const global differ from a non-const global in this way in C++ compared to C? What is happening under the covers with C++ and C with respect to const?
For example this is allowed in C++, but wrong in C:
// Foo.cpp const int Foo = 99; // Main.cpp const int Foo = 99; int main() { cout << Foo << endl; return 0; }
And this is fine with C, but wrong with 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
variable at namespace scope has internal linkage. So they're basically two different variables. There is no redefinition.From @David's comment, 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.
In the second case, you should be doing this (correct way):
//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; }
这篇关于为什么一个const全局变量的多个定义在C ++和不是在C允许?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!