Can a variable be declared both static and extern?

后端 未结 4 972
后悔当初
后悔当初 2020-12-03 10:50

Why the following doesn\'t compile?

...
extern int i;
static int i;
...

but if you reverse the order, it compiles fine.

...         


        
4条回答
  •  孤城傲影
    2020-12-03 11:01

    C++:

    7.1.1 Storage class specifiers [dcl.stc]

    7) A name declared in a namespace scope without a storage-class-specifier has external linkage unless it has internal linkage because of a previous declaration and provided it is not declared const. Objects declared const and not explicitly declared extern have internal linkage.

    So, the first one attempts to first gives i external linkage, and internal afterwards.

    The second one gives it internal linkage first, and the second line doesn't attempt to give it external linkage because it was previously declared as internal.

    8) The linkages implied by successive declarations for a given entity shall agree. That is, within a given scope, each declaration declaring the same variable name or the same overloading of a function name shall imply the same linkage. Each function in a given set of overloaded functions can have a different linkage, however.
    [ Example:

    [...]
    static int b; // b has internal linkage
    extern int b; // b still has internal linkage
    [...]
    extern int d; // d has external linkage
    static int d; // error: inconsistent linkage
    [...]
    

提交回复
热议问题