为什么"extern const int n;"不能按预期工作?

Why does "extern const int n;" not work as expected?

本文关键字:不能按 工作 extern const int 为什么      更新时间:2023-10-16

我的项目只包含两个源文件:

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

我知道有几种方法可以使其工作;但是,我只是想知道为什么它不起作用?

这是因为默认情况下const意味着内部链接,所以您的"定义"在翻译单元之外不可见它出现的地方。

在这种情况下,到目前为止,最好的解决方案是将声明( extern int const n; ( 在头文件中,并将其包含在a.cppb.cpp. 联动由编译器看到的第一个声明,因此后面的定义 a.cpp将具有正确的(外部(链接。

或者,您可以在定义中强制链接:

extern int const n = 8;

尽管有extern,这仍然是一个定义;任何有类定义之外的初始值设定项是一个定义。

C++中的constconstexpr变量具有内部链接(因此在其他编译单元中无法访问(,如果它们没有extern声明(无论是在定义中还是在以前的声明中(。

在 C 语言中,情况并非如此(C 没有constexpr(,所以你的代码是有效的,你可以把更多的代码放在定义上extern

因此,如果你想编写既是C又是C++的代码(这两个声明可能应该来自詹姆斯指出的同一个标头(:

// a.cpp
extern const int n;
const int n = 8;
// b.cpp
extern const int n;
int main()
{
    int m = n; 
}

如果你不这样做

// a.cpp
extern const int n = 8;

也是可能的

在 a 中声明它 extern.cpp并在 b.cpp 中不使用 extern:

A.H

extern const int n ;

答.cpp

#include "a.h"
...
const int n= 8

b.cpp:

#include "a.h"
...

int main()
{        
    int m = n; 
}

To share a const object among multiple files, you must define the variable as extern.

To define a single instance of a const variable, we use the keyword extern on both its definition and declaration(s):

根据这些规则,您只需要在定义中添加 extern 关键字。 你已经在声明中拥有它。

如果这里的其他答案不起作用,则可能是您的定义在不同的命名空间中......如果编译通过,并且您收到undefined symbol链接器错误:

  • 检查未定义符号的命名空间;这是extern const int n声明的有效命名空间。
  • 确保这是您在其中进行const int n = 8定义的有效命名空间。