externconstint n;int main(){// error LNK2001: unresolved external symbol "int const n" (?n@@3HB)int m = n;}
I know there are several methods to make it work; however, I just wonder WHY it does't work?
It's because const implies internal linkage by default, soyour "definition" isn't visible outside of the translation unitwhere it appears.
In this case, by far the best solution is to put the declaration(extern int const n;) in a header file, and include that inbotha.cpp andb.cpp. The linkage is determined by thefirst declaration the compiler sees, so the later definition ina.cpp will have the correct (external) linkage.
Alternatively, you can force the linkage in the definition:
externintconst n =8;
Despite the extern, this is still a definition; anything withan initializer outside of a class definition is a definition.
2.extern修饰函数声明。从本质上来讲,变量和函数没有区别。函数名是指向函数二进制块开头处的指针。如果文件a.c需要引用b.c中的函数,比如在b.c中原型是intfun(int mu),那么就可以在a.c中声明extern int fun(intmu),然后就能使用fun来做任何事情。就像变量的声明一样,extern int fun(intmu)可以放在a.c中任何地方,而不一定非要放在a.c的文件作用域的范围中。对其他模块中函数的引用,最常用的方法是包含这些函数声明的头文件。使用extern和包含头文件来引用函数有什么区别呢?extern的引用方式比包含头文件要简洁得多!extern的使用方法是直接了当的,想引用哪个函数就用extern声明哪个函数。这大概是KISS原则的一种体现吧!这样做的一个明显的好处是,会加速程序的编译(确切的说是预处理)的过程,节省时间。在大型C程序编译过程中,这种差异是非常明显的。