为什么“extern const int n;”不按预期工作? [英] Why does "extern const int n;" not work as expected?
问题描述
我的专案只有两个来源档案:
My project consists of only two source files:
a.cpp:
const int n = 8;
b.cpp:
extern const int n;
int main()
{
// error LNK2001: unresolved external symbol "int const n" (?n@@3HB)
int m = n;
}
我知道有几种方法可以使它工作;
I know there are several methods to make it work; however, I just wonder WHY it does't work?
推荐答案
这是因为 const
默认表示内部链接,所以
你的定义在翻译单元
外面是不可见的。
It's because const
implies internal linkage by default, so
your "definition" isn't visible outside of the translation unit
where it appears.
在这种情况下,到目前为止最好的解决方案是将声明
( extern int const n;
)放在头文件中,并将其包含在
a.cpp
和 b.cpp
。链接由编译器看到的
第一个声明确定,因此
a.cpp
中的后面的定义将具有正确的(外部)链接。
In this case, by far the best solution is to put the declaration
(extern int const n;
) in a header file, and include that in
both a.cpp
and b.cpp
. The linkage is determined by the
first declaration the compiler sees, so the later definition in
a.cpp
will have the correct (external) linkage.
或者,您可以在定义中强制进行链接:
Alternatively, you can force the linkage in the definition:
extern int const n = 8;
尽管 extern
定义;任何带有
的初始化程序在类定义之外是一个定义。
Despite the extern
, this is still a definition; anything with
an initializer outside of a class definition is a definition.
这篇关于为什么“extern const int n;”不按预期工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!