In C + +, variables defined or declared within a function body or in a code snippet are scoped to the corresponding function or code snippet, which is a local variable that performs an automatic release of end memory. As opposed to local variables, the definition and declaration of global variables are outside the function body, and the scope ends from the definition to the corresponding file. The use of global variables is divided into the following:
1. A global variable is defined in the file, which needs to be used before: declare it with the extern keyword before defining it. eg
CPP file
extern int A;
void SetA ()
{
a = +;
}
int A;
int main ()
{
//...
}
To use a before the definition of a, it must be declared with the extern keyword before use.
2. Global variables are defined in a CPP file and need to be used in other files: you need to use the extern statement before the other file where you need to be used:
CPP1 file
extern int A; declare
void SetA () {
a = n;
}
CPP2 file, A's definition file
int A; Global variable A's definition
int main ()
{
//...
}
3. A global variable is defined in a CPP file, but only the variable needs to be used in this file: This is the need to add the static keyword at the time of definition.
CPP1 file
extern int A; Invalid declaration, A is only valid in cpp2 file
void SetA () {
a = M
}
CPP2 file, A's definition file
static int A; Global variable A's definition
int main ()
{
//...
}
In the code above, there will be an error in compiling. Because the global variable defined in CPP2 uses the static keyword, its scope is only within that CPP file and cannot be used in other CPP and files.
Attention:
1: When you need to pass data between multiple files or messages, you can use global variables. But you need to be careful not to use a global variable in many places, which can easily cause errors and make it difficult to find errors.
2: Global variables are best to initialize variables when they are defined or declared.