The fact that the declaration extern int x;
refers to int x;
declared at file scope is an example of how linkage works. An identifier specifying an object or function may have one of the following linkages:
- Identifiers with external linkage represent the same object or function in any translation unit (i.e. source file and included headers) in the program.
- Identifiers with internal linkage represent the same object or function in one particular translation unit.
- Identifiers with no linkage represent a distinct object and only exist in the scope in which they are declared.
In your example, int x;
at file scope has external linkage because it was not declared with the static
storage class specifier.
int x;
declared in the outermost block of the main
function has no linkage because there is no storage class specifier on it, so this declaration defines a new object which masks x
declared at file scope.
Now you have extern int x;
declared in a sub-block inside of main
. Because this identifier is declared with extern
, it is compared with the prior visible declaration, specifically x
declared in block scope above it. Since this prior declaration has no linkage, this new identifier has external linkage (it would have internal linkage if the prior declaration had internal linkage). This is described in more detail in section 6.2.2p4 of the C standard:
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.
And because it has external linkage, it refers to the same object as int x;
declared at file scope.