且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-09 20:45:16

// Foo.cpp
const int Foo = 99;

// Main.cpp
const int Foo = 99;

命名空间范围内的

const 变量具有 internal 链接.所以它们基本上是两个不同的变量.没有重新定义.

const variable at namespace scope has internal linkage. So they're basically two different variables. There is no redefinition.

来自@David 的评论,3.5/3 [basic.link]:

From @David's comment, 3.5/3 [basic.link]:

具有命名空间范围的名称 (3.3.5)如果是名称,则具有内部链接
— 对象、引用、函数或显式的函数模板声明为静态或,
— 一个物体或明确声明的引用const 且均未明确声明extern 之前也没有声明过外部链接;或
— 数据成员一个匿名工会的成员.

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;
}