V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
codechaser
V2EX  ›  C++

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

  •  
  •   codechaser · 2019-08-06 16:50:08 +08:00 · 2338 次点击
    这是一个创建于 1696 天前的主题,其中的信息可能已经有所发展或是发生改变。

    各位好,今天在别人博客上看到个问题,我想了一下没想出来。求教: 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也是可以的。

    5 条回复    2019-08-07 22:48:19 +08:00
    lonewolfakela
        1
    lonewolfakela  
       2019-08-06 16:58:10 +08:00   ❤️ 1
    C++中的 const 附带 imply "internal linkage" ,大体上可以理解为 const 默认就是 const static。
    nmgwddj
        2
    nmgwddj  
       2019-08-07 10:28:43 +08:00 via iPhone
    @lonewolfakela 学习了
    codechaser
        3
    codechaser  
    OP
       2019-08-07 20:55:42 +08:00 via Android
    @lonewolfakela thank you!
    codechaser
        4
    codechaser  
    OP
       2019-08-07 20:56:22 +08:00 via Android
    @lonewolfakela 既然是 static,为啥声明了 extern 就可以了?
    lonewolfakela
        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.”
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2995 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 14:42 · PVG 22:42 · LAX 07:42 · JFK 10:42
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.