C++ Programming
The extern
keyword tells the compiler that a variable is defined in another source module (outside of the current scope). The linker then finds this actual declaration and sets up the extern
variable to point to the correct location. Variables described by extern
statements will not have any space allocated for them, as they should be properly defined elsewhere. If a variable is declared extern, and the linker finds no actual declaration of it, it will throw an "Unresolved external symbol" error.
Examples:
extern int i;
- declares that there is a variable named i of type int, defined somewhere in the program.
extern int j = 0;
- defines a variable j with external linkage; the
extern
keyword is redundant here.
extern void f();
- declares that there is a function f taking no arguments and with no return value defined somewhere in the program;
extern
is redundant, but sometimes considered good style.
extern void f() {;}
- defines the function f() declared above; again, the
extern
keyword is technically redundant here as external linkage is default.
extern const int k = 1;
- defines a constant int k with value 1 and external linkage; extern is required because const variables have internal linkage by default.
extern
statements are frequently used to allow data to span the scope of multiple files.
When applied to function declarations, the additional "C" or "C++" string literal will change name mangling when compiling under the opposite language. That is, extern "C" int plain_c_func(int param);
allows C++ code to execute a C library function plain_c_func.