V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
codechaser
V2EX  ›  C++

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

  •  
  •   codechaser · Aug 6, 2019 · 2951 views
    This topic created in 2456 days ago, the information mentioned may be changed or developed.

    各位好,今天在别人博客上看到个问题,我想了一下没想出来。求教: 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 replies    2019-08-07 22:48:19 +08:00
    lonewolfakela
        1
    lonewolfakela  
       Aug 6, 2019   ❤️ 1
    C++中的 const 附带 imply "internal linkage" ,大体上可以理解为 const 默认就是 const static。
    nmgwddj
        2
    nmgwddj  
       Aug 7, 2019 via iPhone
    @lonewolfakela 学习了
    codechaser
        3
    codechaser  
    OP
       Aug 7, 2019 via Android
    @lonewolfakela thank you!
    codechaser
        4
    codechaser  
    OP
       Aug 7, 2019 via Android
    @lonewolfakela 既然是 static,为啥声明了 extern 就可以了?
    lonewolfakela
        5
    lonewolfakela  
       Aug 7, 2019
    @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.”
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1505 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 16:49 · PVG 00:49 · LAX 09:49 · JFK 12:49
    ♥ Do have faith in what you're doing.