#ifndef #define #endif防止的是 "repeating compilation" instead of "repeating definition"
Duplicate compilation can result in duplicate definitions, but duplicate definitions are not the only source of duplicate compilation
It takes two steps to turn from code into an executable program
Compiling and linking
The code to replace all # include header files with the header file at the beginning of compilation
In the compilation phase, all the source files are compiled into modules, and each variable and function in each module gets its own space.
In the link phase, each module is grouped together
#ifndef能够防止在编译阶段, a piece of code is compiled repeatedly, and thus prevents a variable from being repeatedly defined
But it does not prevent the link phase, each module has a variable called a name, so the link error: Variable definition
The workaround is not only to prevent duplicate compilation with the #ifndef combination, but also to define the variable in the source file, and only place the extern declaration in the header file.
When the modules are compiled, it is known that "there is such a variable, but it is not in my space", when linked, this variable appears in all the modules containing the header file, but only one module is its true location
C + + Engineering Repetitive compilation and duplicate definition