Example:
Header file: state.h source file: State.cpp
Other source files: T1.cpp t2.cpp t3.cpp, these source files contain header file state.h.
You need to define a global variable for use in these source files:
1. Declare global variables in state.h: extern int A;
2. Define the global variable in state.cpp: int a = 10;
This allows the variable to be used by other source files.
What is needed here is "declaration", not "definition"! According to the C + + standard, a variable declaration must satisfy two conditions at the same time, otherwise it is defined as:
(1) The declaration must use the extern keyword; (2) cannot assign an initial value to a variable
extern int A; Statement
int A; Defined
int a = 0; Defined
extern int a = 0; Defined
The header file should use the extern keyword to declare the global variable (not defined), if the variable has more than one file to use, you can create a new CPP, defined in it, the CPP into the project. header file Please do not define any variables, that is very amateur behavior ...
Generally stated in the header file, with extern, defined in CPP. If defined in the header file, if the header file is referenced by more than one CPP, it causes a duplicate-defined link error.
Header files can only declare global variables (extern), not defined (deprecated). cpp, in the outermost definition (int gi), direct reference
If the static definition is used in. cpp, the variable is valid only in the current CPP file and is not valid in another file
Using the static definition in. h does not compile (the. h file does not compile) and only contains the compilation in the CPP file for each of its include, which is equivalent to using the static definition in. cpp.
C + + multiple source files share a global variable (extern usage)