通常,extern 关键字告诉编译器不要定义符号,因为它将在其他地方定义。所以写例如
namespace Bob {
extern T x;
}
没有定义变量x,而是声明它。您可以拥有任意数量的extern 声明。但是,如果您不提供定义,则链接将失败。所以你必须定义
T Bob::x;
在代码中的某个地方提供定义。
const 关键字在这里有点特别,因为它暗示了内部链接。这意味着,x 的定义在定义它的特定编译单元之外将不可见。要改变这种行为,你需要写
extern const T Bob::x = 123;
如果您希望 x 成为 const 并从其他编译单元中引用它。
----又一次修改----
只是要绝对清楚:
如果应该在其编译单元之外引用 const 变量,那么您必须显式声明它 extern。
但是,如果声明与定义分开给出,那么定义不一定需要再次指定关键字extern。另一个演示示例:
myheader.h
extern const int i;
这声明了i 一个带有外部链接的const 整数,但没有定义它。
main.cpp,版本 1
#include "myheader.h" //Through the include, the above declaration of `i` comes before its definition.
const int i=123; // Although the `extern` modifier is omitted here,
// it's still in effect because we already declared `i` as `extern`
// Therefore it makes no difference here, whether or not you specify `extern` again.
// The compiler knows this is a definition either way, because of the initialization.
main.cpp,第 2 版
//#include "myheader.h"
extern const int i=123; // this line is declaration and definition in one, because we did not include
// the declaration from myheader.h. Thus, to tell the compiler that you want
// `i` with external linkage, you MUST specify `extern`. Otherwise you'll get
// internal linkage.
我希望现在这一切对你有意义。