Possible Duplicate:
Effects of the `extern` keyword on C functions
Ok, so for a few hours now I’ve read a lot about what the extern keyword means. And there is one last thing that is bugging me to no end that I cannot find any info about.
As far as I understand the extern keyword basically tells the compiler that the variable or function is only a declaration and that it is defined somewhere, so it doesn’t have to worry about that, the linker will handle it.
And the warning generated by the compiler (I’m using gcc 4.2.1) when typing this:
extern int var = 10;
supports this. With extern this should be a declaration only so it is not correct.
However, the thing that is confusing me is the absence of a warning or anything when typing this:
extern int func() {return 5;}
This is a definition, and it should generate the same warning, but it does not. The only explanation to this I was able to find here is that the definition overrides the extern keyword. However, following that logic why does it not override it when it is a variable definition? Or does the keyword have special meaning when used with variables?
I would be most grateful if someone explained this to me. Thank you!
The
externkeyword indeed has special meaning only when it is used with variables. Usingexternwith function prototypes is entirely optional:is equivalent to
When you declaring/defining a function, you have two options:
With variables, however, you have three options:
int var;without the= 10part, orint var = 10Since there are only two options for functions, the compiler can distinguish between then without the use of
externkeyword. Any declaration that does not have astatickeywords is consideredexternby default. Therefore, theexternkeyword is ignored with all function declarations or definitions.With variables, however, the keyword is needed to distinguish between the #1 and the #2. When you use
extern, it’s #1; when you do not useextern, it’s #2. When you try to addexternto #3, it’s a warning, because it remains a definition, and theexternis ignored.All of this is somewhat simplified: you can provide declarations several times in the same compilation unit, and you can provide them at the global scope or at a block scope. For complete details, check section 6.7.9 5 of the C standard.