What is the usage of the “extern” keyword in C++?
In C++, the keyword ‘extern’ is used to declare the existence of external variables or functions.
- When it comes to variables, if we define a global variable in one file and want to use it in another file, we need to declare its existence using the “extern” keyword in the other file. This way, the compiler knows that the variable is defined in another file and can link them together.
Define global variables in a file.
// File1.cpp
int globalVariable = 10;
Use the variable in another file.
// File2.cpp
extern int globalVariable; // 使用extern关键字声明全局变量的存在
void someFunction() {
int localVar = globalVariable; // 使用全局变量
}
- When using the same function in multiple files, we need to declare its existence using the extern keyword so that the compiler knows the function is defined in other files and can link them together.
Define a function in a file.
// File1.cpp
void someFunction(); // 函数声明
void someFunction() {
// 函数定义
}
Use the function in another file:
// File2.cpp
extern void someFunction(); // 使用extern关键字声明函数的存在
void anotherFunction() {
someFunction(); // 调用函数
}
Summary: The “extern” keyword is used to declare the existence of global variables or functions in other files. It tells the compiler to link them together during the linking phase.