What is the purpose of the “extern” keyword in C++?
In C++, the keyword ‘extern’ is used to declare a variable or function that is defined elsewhere, meaning its definition is in another source file. This keyword tells the compiler to use the variable or function in the current file, rather than defining it in the current file.
Using the “extern” keyword, we can declare a variable or function in one source file, define it in another source file, and use it wherever needed. This is very useful in large projects as it allows us to divide the code into multiple files, improving code readability and maintainability.
If a variable or function is not declared with the “extern” keyword, the compiler will assume that it is defined in the current file and will process it accordingly during compilation.
Here are two common uses of the “extern” keyword:
- external
- external
For example, declaring a global variable in file A.cpp:
// A.cpp
extern int globalVariable;
Define the global variable in file B.cpp.
// B.cpp
int globalVariable = 10;
Then you can use the global variable wherever needed.
// C.cpp
extern int globalVariable;
int main() {
// 使用globalVariable
return 0;
}
By using the extern keyword, we can utilize global variables defined in file B.cpp in file C.cpp.