Main. cpp
# Include "global. h"
Int Main (....)
{
...
}
File_1.cpp
# Include "global. h"
....
File_2.cpp
# Include "global. h"
...
Write all global variables, their initialization values, and function declarations in global. h.
Errors occur during compilation:
First defined here
Multiple definition
The reason is that variables and functions are repeatedly defined when global. h is included for multiple times.
Solution:
Method 1:
Declare the variable (not initialized) in global. c (or. cpp), and add extern before all the variable declarations in the header file global. h.
For example, extern int flag;
The. h file is included in other cpp files that require global variables instead of the. cpp file. The compiler will generate the target file for global. cpp, and then connect to the file when using global variables.
Method 2:
Add macro judgment symbols to global. h to prevent repeated Definitions
Add Conditional compilation to your. H file.
# Ifndef GLOBAL
# Define GLOBAL
XXXXX
XXXXX
# Endif
Remember: ifndef must be in the first line, and there should be no comments or statements in the front.