152 down vote accepted
"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. |
extern tells the compiler that this data is defined somewhere and will be connected with the linker.
With the help of the responses here and talking to a few friends here is the practical example of a use ofextern.
Example 1 - to show a pitfall:
File stdio.h:
int errno;
/* other stuff...*/
myCFile1.c:
#include <stdio.h>
Code...
myCFile2.c:
#include <stdio.h>
Code...
If myCFile1.o and myCFile2.o are linked, each of the c files have separate copies oferrno. This is a problem as errno is suppose to be constant over all linked files.
Example 2 - The fix.
File stdio.h:
extern int errno;
/* other stuff...*/
File stdio.c
int errno;
myCFile1.c:
#include <stdio.h>
Code...
myCFile2.c:
#include <stdio.h>
Code...
Now if both myCFile1.o and MyCFile2.o are linked by the linker they will both p
转自:http://stackoverflow.com/questions/496448/how-to-correctly-use-the-extern-keyword-in-c |