Example:
Header file: state.h source file: State.cpp
Other source files: T1.cpp t2.cpp t3.cpp, these source files all contain header file state.h.
You need to define a global variable for use in these source files: The following methods
1, declare the global variable in state.h: extern int A;
2. Define the global variable in state.cpp: int a = 10;
This allows other source files to use the variable.
What is required here is "declaration", not "definition". According to the C + + standard, a variable declaration must satisfy two conditions, otherwise it is defined as:
(1) 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 a global variable (undefined), if the variable has multiple files, you can create a new CPP, define it, and add the CPP to the project. Header file Please do not define any variables, it 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 multiple CPP, it can cause a duplicate-defined link error.
header files can only declare global variables (extern), not defined (not recommended) . cpp, in the outermost definition can (int gi), direct reference
If a 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 (. h files are not compiled), only contains the compilation in each of its included CPP files, which is equivalent to using the static definition in. cpp.
Reproduced from: http://blog.sina.com.cn/s/blog_74a459380101rjh4.html