My question is about when a function should be referenced with the extern
keyword in C.
I am failing to see when this should be used in practice. As I
In C, 'extern' is implied for function prototypes, as a prototype declares a function which is defined somewhere else. In other words, a function prototype has external linkage by default; using 'extern' is fine, but is redundant.
(If static linkage is required, the function must be declared as 'static' both in its prototype and function header, and these should normally both be in the same .c file).
It has already been stated that the extern
keyword is redundant for functions.
As for variables shared across compilation units, you should declare them in a header file with the extern keyword, then define them in a single source file, without the extern keyword. The single source file should be the one sharing the header file's name, for best practice.
When you have that function defined on a different dll or lib, so that the compiler defers to the linker to find it. Typical case is when you are calling functions from the OS API.
All declarations of functions and variables in header files should be extern
.
Exceptions to this rule are inline functions defined in the header and variables which - although defined in the header - will have to be local to the translation unit (the source file the header gets included into): these should be static
.
In source files, extern
shouldn't be used for functions and variables defined in the file. Just prefix local definitions with static
and do nothing for shared definitions - they'll be external symbols by default.
The only reason to use extern
at all in a source file is to declare functions and variables which are defined in other source files and for which no header file is provided.
Declaring function prototypes extern
is actually unnecessary. Some people dislike it because it will just waste space and function declarations already have a tendency to overflow line limits. Others like it because this way, functions and variables can be treated the same way.