9

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?

Pubby
  • 51,882
  • 13
  • 139
  • 180

3 Answers3

7

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..

Community
  • 1
  • 1
Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
2

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.

selalerer
  • 3,766
  • 2
  • 23
  • 33
0

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).

ninjalj
  • 42,493
  • 9
  • 106
  • 148