c++访问其他源文件定义的数组

2019-08-06 16:50:08 +08:00
 codechaser

各位好,今天在别人博客上看到个问题,我想了一下没想出来。求教: 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不需要加externarray_test需要加,而且将array_test定义里的const去掉,那么不加extern也是可以的。

2358 次点击
所在节点    C++
5 条回复
lonewolfakela
2019-08-06 16:58:10 +08:00
C++中的 const 附带 imply "internal linkage" ,大体上可以理解为 const 默认就是 const static。
nmgwddj
2019-08-07 10:28:43 +08:00
@lonewolfakela 学习了
codechaser
2019-08-07 20:55:42 +08:00
@lonewolfakela thank you!
codechaser
2019-08-07 20:56:22 +08:00
@lonewolfakela 既然是 static,为啥声明了 extern 就可以了?
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.”

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/589550

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX