各位好,今天在别人博客上看到个问题,我想了一下没想出来。求教: test.cpp:
int foo = 555;
const int array_test[5] = {1,2,3,4,5};
main.cpp:
#include <iostream>
extern int a;
extern const int array_test[5];
int main(void)
{
std::cout<<a<<std::endl;
std::cout<<array_test[0]<<std::endl;
}
这里这样写a可以访问,但array_test显示未定义。需要在 test.cpp 中的const int array_test[5] = {1,2,3,4,5};前加上extern才可以。那么这是为什么呢?a不需要加extern,array_test需要加,而且将array_test定义里的const去掉,那么不加extern也是可以的。
1
lonewolfakela 2019-08-06 16:58:10 +08:00 C++中的 const 附带 imply "internal linkage" ,大体上可以理解为 const 默认就是 const static。
|
2
nmgwddj 2019-08-07 10:28:43 +08:00 via iPhone
@lonewolfakela 学习了
|
3
codechaser OP @lonewolfakela thank you!
|
4
codechaser OP @lonewolfakela 既然是 static,为啥声明了 extern 就可以了?
|
5
lonewolfakela 2019-08-07 22:48:19 +08:00
@codechaser
Appendix C (C++11, C.1.2) “ Change: A name of file scope that is explicitly declared const, and not explicitly declared extern, has internal linkage, while in C it would have external linkage Rationale: Because const objects can be used as compile-time values in C++, this feature urges programmers to provide explicit initializer values for each const. This feature allows the user to put const objects in header files that are included in many compilation units.” |