C extern Keyword
Example
Use a global variable that is defined after main():
extern int myNum; // Declared here, defined below
int main() {
printf("%d", myNum);
return 0;
}
int myNum = 15; // The definition
Definition and Usage
The extern keyword declares a variable or function that is defined somewhere else, usually in another file. A declaration tells the compiler that something exists. A definition creates it.
It is mostly used in programs with many source files. Put the extern line in a header file, so that every file that includes it can use the same variable.
In the example, myNum is defined after main(). Without the extern line, main() could not use myNum, because the compiler has not seen it yet.
Related Pages
Read more about extern in our C Storage Classes Tutorial.
Read more about programs with many files in our C Organize Code Tutorial.