What is the usage of the “extern” keyword in C++?
In C++, the “extern” keyword is used to declare a global variable or function that is defined in another file. Its purpose is to instruct the compiler to not require the definition of this variable or function in the current file, but instead to look for it in another file when used in the current file.
The specific usage is as follows:
- Declare global variables in other files using the extern keyword to declare them as external variables, and then use the variable in the current file.
// external.cpp
int globalVar = 10;
// main.cpp
extern int globalVar;
int main() {
// 使用外部变量globalVar
// ...
return 0;
}
- When defining a function in other files, declare it as an external function using the keyword “extern” and then call that function in the current file.
// external.cpp
void externalFunc() {
// ...
}
// main.cpp
extern void externalFunc();
int main() {
// 调用外部函数externalFunc
externalFunc();
return 0;
}
It is important to note that the “extern” keyword is used for declaration only and does not allocate memory space. The actual variable or function definitions must be made in another file.