我的项目仅包含两个源文件:
一个.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;
}
我知道有几种方法可以使它起作用;但是,我只是想知道为什么它不起作用?
我的项目仅包含两个源文件:
一个.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.cpp和b.cpp中。链接由编译器看到的第一个声明确定,因此后面的定义
a.cpp将具有正确的(外部)链接。
或者,您可以强制定义中的链接:
extern int const n = 8;
尽管如此extern,这仍然是一个定义;任何在类定义之外带有初始化器的东西都是定义。
const如果 C++ 中的和变量未声明(在定义中或在先前的声明中),constexpr则它们具有内部链接(因此在其他编译单元中不可访问)。extern
在 C 中,情况并非如此(C 没有constexpr),因此您的代码是有效的,并且您可以添加更多extern定义。
因此,如果您想编写同时是 C 和 C++ 的代码(并且这两个声明可能应该来自 James 指出的同一个标头):
// 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.cpp 中声明它为 extern,并在 b.cpp 中不使用 extern:
啊
extern const int n ;
a.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):
From these rules you just need to add the extern keyword in your definition. you already have it in declaration.
如果此处的其他答案不能解决问题,则可能是您在不同的命名空间中有定义......如果编译通过,并且您收到undefined symbol链接器错误:
extern const int n。const int n = 8定义的有效命名空间。