Solve the problem of multiple definition of in C/C ++-C ++ Language Program Development Technical Article _ c ++ programming-
-
Solve the problem of multiple definition of in C/C ++
-
15:06:17 let me say something
- FavoritesI want to contribute
-
main. cpp
# include "Global. H"
int main (...)
{< br>...
}
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.
an error occurs during compilation:
first defined here
multiple definition of
the reason is that variables and functions are repeatedly defined when global. H is included for multiple times.
solution:
Method 1:
in global. C (or. CPP), and then the header file global. h add extern before all variable declarations.
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:
. h: Add macro judgment symbols that prevent repeated definitions
your. add Conditional compilation in H
# ifndef global
# define global
XXXXX
# endif
remember: ifndef must be in the first line without any comments or statements on the front.