Include guards do protect header files from mutual, recursive inclusion.
The problem arises when there are dependencies between the definitions of data structures in mutually-including headers. For example:
// a.h #include "b.h" struct A { ... }; // b.h #include "a.h" struct B { A* pA; // error: class A is forward-declared but not defined };
To resolve this, forward declarations should be used instead of include guards:
// b.h #include "a.h" // Forward declaration of A struct A; struct B { A* pA; };
Include guards do protect a header from redundant inclusions in the same translation unit. However, multiple definitions can still occur due to their presence in different translation units.
To resolve this, the inline keyword can be used to allow multiple definitions in different translation units:
// header.h inline int f() { ... }
Alternatively, the function definition can be moved to a separate source file to prevent multiple definitions:
// source.cpp int f() { ... }
The above is the detailed content of Why Do Include Guards Fail to Prevent Mutual Recursion and Multiple Definitions?. For more information, please follow other related articles on the PHP Chinese website!