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:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
|
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:
1 2 3 4 5 6 |
|
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:
1 2 3 4 |
|
Is included in multiple translation units, such as source1.cpp and source2.cpp:
1 2 3 4 5 |
|
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!