lillq lillq - 9 days ago 6
C Question

How to correctly use the extern keyword in C

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?

Answer

"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.

Comments