I know that global variables in C sometimes have the extern
keyword. What is an extern
variable? What is the declaration like? What is its scope?
This is related to sharing variables across source files, but how does that work precisely? Where do I use extern
?
extern tells the compiler to trust you that the memory for this variable is declared elsewhere, so it doesnt try to allocate/check memory.
Therefore, you can compile a file that has reference to an extern, but you can not link if that memory is not declared somewhere.
Useful for global variables and libraries, but dangerous because the linker does not type check.
GCC ELF Linux implementation
main.c
:Compile and decompile:
Output contains:
The System V ABI Update ELF spec "Symbol Table" chapter explains:
which is basically the behavior the C standard gives to
extern
variables.From now on, it is the job of the linker to make the final program, but the
extern
information has already been extracted from the source code into the object file.Tested on GCC 4.8.
extern
simply means a variable is defined elsewhere (e.g., in another file).