Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can extern be applied to definitions?

Tags:

c++

c

extern

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?

like image 597
Pubby Avatar asked Oct 23 '11 14:10

Pubby


2 Answers

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

like image 90
Johannes Schaub - litb Avatar answered Oct 12 '22 08:10

Johannes Schaub - litb


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.

like image 33
selalerer Avatar answered Oct 12 '22 09:10

selalerer