Can a variable be declared both static and extern?

后端 未结 4 973
后悔当初
后悔当初 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:16

    For C, quoting the standard, in C11 6.2.2: Linkage of identifiers:

    3) If the declaration of a file scope identifier for an object or a function contains the storage-class specifier static, the identifier has internal linkage.

    4) For an identifier declared with the storage-class specifier extern in a scope in which a prior declaration of that identifier is visible, if the prior declaration specifies internal or external linkage, the linkage of the identifier at the later declaration is the same as the linkage specified at the prior declaration. If no prior declaration is visible, or if the prior declaration specifies no linkage, then the identifier has external linkage.

    (emphasis-mine)

    That explains the second example (i will have internal linkage). As for the first one, I'm pretty sure it's undefined behavior:

    7) If, within a translation unit, the same identifier appears with both internal and external linkage, the behavior is undefined.

    ...because extern appears before the identifier is declared with internal linkage, 6.2.2/4 does not apply. As such, i has both internal and external linkage, so it's UB.

    If the compiler issues a diagnostic, well lucky you I guess. It could compile both without errors and still be compliant to the standard.

提交回复
热议问题