What is external linkage and internal linkage?

前端 未结 9 1202
情深已故
情深已故 2020-11-22 00:10

I want to understand the external linkage and internal linkage and their difference.

I also want to know the meaning of

const va

9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 00:15

    As dudewat said external linkage means the symbol (function or global variable) is accessible throughout your program and internal linkage means that it's only accessible in one translation unit.

    You can explicitly control the linkage of a symbol by using the extern and static keywords. If the linkage isn't specified then the default linkage is extern for non-const symbols and static (internal) for const symbols.

    // in namespace or global scope
    int i; // extern by default
    const int ci; // static by default
    extern const int eci; // explicitly extern
    static int si; // explicitly static
    
    // the same goes for functions (but there are no const functions)
    int foo(); // extern by default
    static int bar(); // explicitly static 
    

    Note that instead of using static for internal linkage it is better to use anonymous namespaces into which you can also put classes. The linkage for anonymous namespaces has changed between C++98 and C++11 but the main thing is that they are unreachable from other translation units.

    namespace {
       int i; // external linkage but unreachable from other translation units.
       class invisible_to_others { };
    }
    

提交回复
热议问题