C++ extern Keyword
Example
Declare a variable that is defined later in the file:
extern int myNum; // Declaration
int main() {
cout << myNum;
return 0;
}
int myNum = 15; // Definition
Definition and Usage
The extern keyword declares a variable without creating it. It tells the compiler that the variable is defined (created) somewhere else, often in another file of the same program.
This is useful when many files need the same global variable. Define the variable in one file, and declare it with extern in the other files. In the example, the variable is defined after main(), in the same file.
Functions are extern by default, so you rarely need to write extern in front of a function.
Related Pages
Read more about global variables in our C++ Variable Scope Tutorial.