How to use external variables in C++
In C++, an external variable can be declared using the extern keyword. The specific steps are as follows:
- Declare external variables in the definition file using the “extern” keyword. For example, in file A.cpp, an external variable x is defined.
int x;
- In other files where you need to use the external variable, use the keyword “extern” to reference that variable. For example, in file B.cpp, use the external variable x.
extern int x;
- Then you can use the external variable x in the file B.cpp.
int main() {
x = 10;
// 其他操作
return 0;
}
Attention:
- The declaration of external variables only needs to appear once, typically placed in the header file.
- The definition of external variables only needs to appear once, typically placed in one source file.
- External variables can be shared and accessed across different source files.
- The scope of global variables is the entire program.