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 am writing a program all of the functions that I use are made available through the header files I have included. So why would it be useful to extern
to get access to something that was not exposed in the header file?
I could be thinking about how extern
works incorrectly, and if so please correct me.
Edit: Should you extern
something when it is the default declaration without the keyword in a header file?
"
extern
" changes the linkage. With the keyword, the function / variable is assumed to be available somewhere else and the resolving is deferred to the linker.There's a difference between "extern" on functions and on variables: on variables it doesn't instantiate the variable itself, i.e. doesn't allocate any memory. This needs to be done somewhere else. Thus it's important if you want to import the variable from somewhere else. For functions, this only tells the compiler that linkage is extern. As this is the default (you use the keyword "static" to indicate that a function is not bound using extern linkage) you don't need to use it explicitly.
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 withstatic
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.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.