I compile this program by g++ and clang++. There has a difference:
g++ prints 1, but clang++ prints 2.
It seems that
g++: the extern varible is defined in the shorte
[basic.link/7] should be the relevant part of the Standard. In the current draft, it says:
The name of a function declared in block scope and the name of a variable declared by a block scope
extern
declaration have linkage. If such a declaration is attached to a named module, the program is ill-formed. If there is a visible declaration of an entity with linkage, ignoring entities declared outside the innermost enclosing namespace scope, such that the block scope declaration would be a (possibly ill-formed) redeclaration if the two declarations appeared in the same declarative region, the block scope declaration declares that same entity and receives the linkage of the previous declaration. If there is more than one such matching entity, the program is ill-formed. Otherwise, if no matching entity is found, the block scope entity receives external linkage. If, within a translation unit, the same entity is declared with both internal and external linkage, the program is ill-formed.
Note that the subsequent example almost exactly matches your case:
static void f();
extern "C" void h();
static int i = 0; // #1
void g() {
extern void f(); // internal linkage
extern void h(); // C language linkage
int i; // #2: i has no linkage
{
extern void f(); // internal linkage
extern int i; // #3: external linkage, ill-formed
}
}
So, the program should be ill-formed. The explanation is below the example:
Without the declaration at line #2, the declaration at line #3 would link with the declaration at line #1. Because the declaration with internal linkage is hidden, however, #3 is given external linkage, making the program ill-formed.