c++ - 为什么在 C++ 中允许对 const 全局变量进行多重定义,而在 C 中却不允许?

标签 c++ c constants one-definition-rule

由于单一定义规则,在 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/

相关文章:

c - 稀疏矩阵线性和非线性方程求解器

python - PyObject* 的 "String"表示的生命周期

angularjs - 增量添加到 Angular JS 中的现有变量

java - Java 中的 KeyEvent 常量

c++ - boost::log 在 channel 记录器中设置 "Channel"属性

c++ - uint32、int16、uint8 .. 为什么这些常用数据类型没有纳入标准

c - 仅 header 库不使用 header 保护。如何在其他头文件中使用该库?

c++ - 我可以从引用传递的参数返回值声明 const int 吗?

c++ - 如何获取当前用户权限组?

c++ - libvlc 的手册页