考虑以下两个文件。
a. cpp:
#include <string>
namespace a
{
const std::string str = "something";
}
b.cpp:
#include <iostream>
#include <string>
namespace a
{
extern const std::string str;
}
int main(int argc, char **argv)
{
std::cout << a::str;
return 0;
}
当我编译它们的时候,这样(Fedora 30, gcc 9.2.1),我得到了链接器错误:
g++ a.cpp b.cpp -o a
我得到了链接器错误。
/usr/bin/ld: /tmp/ccEtAgEb.o: in function `main':
b.cpp:(.text+0x10): undefined reference to `a::str[abi:cxx11]'
collect2: error: ld returned 1 exit status
有谁能告诉我为什么,如何解决?我想避免在头文件中引用a::str,因为它不是公共接口的一部分,而是命名空间中的一个私有变量。
const std::string str = "something";
应该是
extern const std::string str = "something";
const
在命名空间作用域中限定对象有一个额外的属性,即对其名称施加内部链接。你的原始代码与
static const std::string str = "something";
试着在b.cpp中加入#include "a.cpp",这样你的代码就会正确,外部定义在b中,实现在a中。