Alex Rivera | Logout

How to correctly use the extern keyword in C

Asked 2009-01-30T17:40:38.333
341

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.

Also.. Should you extern something when it is the default declaration without the keyword in a header file?

c
Edit
Report

3 Answers

388

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.

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

answered 2009-01-30T17:49:12.687
16

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

answered 2009-01-30T20:03:42.163
7

If each file in your program is first compiled to an object file, then the object files are linked together, you need extern. It tells the compiler "This function exists, but the code for it is somewhere else. Don't panic."

answered 2009-01-30T17:47:58.833

Your Answer