extern const char*const SOME_CONSTANT给我链接器错误

And*_*Dog 10 c++ linker const extern

我想在API中提供一个字符串常量,如下所示:

extern const char* const SOME_CONSTANT;
Run Code Online (Sandbox Code Playgroud)

但是,如果我在我的静态库源文件中定义它

const char* const SOME_CONSTANT = "test";
Run Code Online (Sandbox Code Playgroud)

我在链接到该库并使用SOME_CONSTANT时遇到链接器错误:

错误1错误LNK2001:未解析的外部符号"char const*const SOME_CONSTANT"(?SOME_CONSTANT @@ 3QBDB)

extern const char* const声明和定义中删除指针const-ness(第二个const关键字)使其工作.如何使用指针常量导出它?

Rei*_*ica 11

问题可能是extern声明在定义常量的源文件中不可见.尝试重复定义上方的声明,如下所示:

extern const char* const SOME_CONSTANT;  //make sure name has external linkage
const char* const SOME_CONSTANT = "test";  //define the constant
Run Code Online (Sandbox Code Playgroud)

  • 而不是重复声明,这与**DRY**(不要重复自己)原则相反,要么(A)在实现中包含头文件,要么(B)仅添加关键字`extern`.好吧,正如我的回答所示.我没有建议代码重复,因为它没有用处:它非常不合适. (4认同)
  • @AndiDog请注意,这与在定义中添加`extern`相同.正如另一个答案所暗示的那样,C++中的`const`意味着`静态`.所以你需要抵消它并明确地在你的定义中说"extern". (3认同)

Che*_*Alf 9

很可能你忘了在你的实现文件中包含你的标题

无论如何,将关键字添加extern到定义中

没有extern声明它具有内部链接,因此链接器不可见