In C extern is a keyword that is used to tell the compiler that the variable that we are declaring was defined elsewhere. In order to fully understand this, you need to know the difference between a definition and a declaration of a variable.
By default it is up to the compiler to decide where to define and where to declare a variable.
When it comes to functions, we declare a function when we write its prototype.
We define a function when we write its body. Therefore there is no point of using the extern keyword with functions.
External variable is one that is defined out of any function. These variables are also called global. extern keyword is of matter only to external variables in a project with more than one file.
Example 1:
file1.c
#include "source1.c" extern int callCount; void someFunction();
file2.c
#include <stdio.h> #include "source2.c" int main() { extern int callCount; printf("%d\n", callCount); someFunction(); printf("%d\n", callCount); return 0; }
In file2 we declare the variable callCount. extern means that this variable is defined elsewhere and we will use that variable – we will not create a new variable here.
Example 2:
In C, we use header files for all declarations. Usually we will put all extern variables there and we will not do any extern declarations in our source files. We will just include the header file and directly use the variables.
myHeader.h
extern int callCount; void printHello();
source1.c
int callCount = 0; void someFunction() { callCount++; // do some stuff here }
main.c
#include <stdio.h> #include "header.h" int main() { int i; printf("The function \"someFunction\" was called %d times.\n", callCount); for(i = 0; i < 5; i++) { someFunction(); printf("The function \"someFunction\" was called %d times.\n", callCount); } return 0; }
Here's how this examples should work:
You should also try it and move things around to get the idea.
The sources from the examples above are availble on GitHub. I also prepared a zip file you. It contains the source and header
files of the examples. You can download it, unzip and create projects
with the source files: c-extern-examples.zip
In conclusion, the extern keyword in C forces a declaration of a variable, that was defined elsewhere. In practice it should be used in our header files and then we will include the necessary headers. We should avoid the usage of exern keyword in our source files.