======== 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.
因為記得文件范圍內的函數和變量默認都是外部鏈接。