Why is this legal?
extern int foo = 0xF00; // Gets a warning, still compiles
extern void bar() { // No warning
int x;
}
Is there a reason to why this is allowed?
Sometimes it's useful
extern const int foo = 0xF00;
Without the extern
, in C++ foo
would be static
and have internal linkage (which means you could not use foo
from another translation unit).
The extern
in both cases in your example is redundant. In C99 an extern
can make a difference for inline
functions..
In the function case, I think it is just like writing:
extern void bar();
void bar()
{
int x;
}
which must be legal since a file with the definition may include a header with such a declaration.
IIUC, in the C standard, a definition is treated just like a declaration with an initializer, so everything that applies to declarations applies equally to definitions.
(Actually, a definition would be a declaration that allocates storage for a variable, so C's tentative definitions (which don't have initializers) would qualify, and those C++'s declarations that act as definitions without having initializers would also qualify. The point that a definition is essentially a declaration plus some added behaviour still applies).