Home > Backend Development > C++ > Why Do Include Guards Fail to Prevent Mutual Recursion and Multiple Definitions?

Why Do Include Guards Fail to Prevent Mutual Recursion and Multiple Definitions?

Susan Sarandon
Release: 2024-12-30 17:20:17
Original
277 people have browsed it

Why Do Include Guards Fail to Prevent Mutual Recursion and Multiple Definitions?

Why aren't include guards preventing mutual, recursive inclusion?

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
};
Copy after login

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;
};
Copy after login

Why aren't include guards preventing multiple definitions?

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()
{
    ...
}
Copy after login

Alternatively, the function definition can be moved to a separate source file to prevent multiple definitions:

// source.cpp
int f()
{
    ...
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template