C++ const变量默认linkage为internal
======== x.cpp =========void print_it();
char const hello[] = "asdf";
int main(int argc, char *argv)
{
print_it();
return 0;
}
======= y.cpp =========
#include <stdio.h>
extern char const hello[1] ;
void print_it()
{
printf("string = %s ", hello );
}
链接时出现下面的错误:
y.obj : error LNK2019: unresolved external symbol "char const * const hello" (?hello@@3QBDB) referenced in function "void __cdecl print_it(void)" (?print_it@@YAXXZ)
原因就是C 中, const变量的默认linkage 规则变了. 要消除上面的错误, 要么使用extern "C", 使它回到C语言的规则中, 要么在x.cpp中 hello的定义处显式地加上extern.
这是在C templates一书中, 8.3.3 小节中一句话的怀疑引起的:
template <char const *str>
class Message;
extern char const hello[] = "Hello, World!";
Message<hello>* hello_msg;
Note the need for the extern keyword because otherwise a const array variable would have internal linkage.
因为记得文件范围内的函数和变量默认都是外部链接。
补充:软件开发 , C++ ,