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:

  1. 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;
  1. 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;
  1. Then you can use the external variable x in the file B.cpp.
int main() {
    x = 10;
    // 其他操作
    return 0;
}

Attention:

  1. The declaration of external variables only needs to appear once, typically placed in the header file.
  2. The definition of external variables only needs to appear once, typically placed in one source file.
  3. External variables can be shared and accessed across different source files.
  4. The scope of global variables is the entire program.
Leave a Reply 0

Your email address will not be published. Required fields are marked *