Home >Backend Development >C++ >Why Are My Include Guards Failing to Prevent Recursive Inclusion and Multiple Symbol Definitions?
Why aren't include guards protecting my header files from mutual, recursive inclusion?
Include guards are doing their job. The issue arises from dependencies between the definitions of data structures in mutually-including headers.
For example, suppose a.h and b.h contain:
// a.h #ifndef A_H #define A_H #include "b.h" struct A {...}; #endif // b.h #ifndef B_H #define B_H #include "a.h" struct B {...}; #endif
Without include guards, main.cpp will not compile due to the compilation depth limit.
With include guards, infinite recursion is prevented. However, dependencies between definitions remain:
To resolve this, use forward declarations in headers that need them:
// b.h #ifndef B_H #define B_H struct A; // Forward declaration struct B {...}; #endif
Why aren't include guards preventing multiple definitions?
Include guards can prevent redefinition within a single translation unit but not across different units.
For example, when header.h:
#ifndef HEADER_H #define HEADER_H int f() {...}; #endif
Is included in multiple translation units, such as source1.cpp and source2.cpp:
// source1.cpp #include "header.h" // source2.cpp #include "header.h"
The linker will complain about multiple definitions of f(), as it sees the same definition in separate object files.
To solve this, use the following approaches:
The above is the detailed content of Why Are My Include Guards Failing to Prevent Recursive Inclusion and Multiple Symbol Definitions?. For more information, please follow other related articles on the PHP Chinese website!