Home > Backend Development > C++ > How Do Include Guards Handle Mutual Recursion and Multiple Symbol Definitions?

How Do Include Guards Handle Mutual Recursion and Multiple Symbol Definitions?

DDD
Release: 2024-12-23 06:17:20
Original
393 people have browsed it

How Do Include Guards Handle Mutual Recursion and Multiple Symbol Definitions?

Why aren't include guards providing mutual recursion protection or preventing multiple symbol definitions?

Mutual Recursion

Include guards do indeed protect your header files from mutual, recursive inclusion. The confusion arises because the issue is not with the guards, but with how data structures are defined in the header files.

Consider the example:

// a.h
#ifndef A_H
#define A_H

#include "b.h"

struct A {
  ...
};

#endif // A_H

// b.h
#ifndef B_H
#define B_H

#include "a.h"

struct B {
  A* pA;
};

#endif // B_H

// main.cpp
#include "a.h"
int main() {
  ...
}
Copy after login

Even with include guards, main.cpp will fail to compile because class A (needed for class B) has an incomplete definition. Forward declarations resolve this issue:

// b.h
#ifndef B_H
#define B_H

// Forward declare A to avoid circular inclusion
struct A;

struct B {
  A* pA;
};

#endif // B_H
Copy after login

Multiple Definitions

Include guards protect against multiple definitions within a single translation unit, but not across different units. To illustrate:

// header.h
#ifndef HEADER_H
#define HEADER_H

int f() {
  return 0;
}

#endif // HEADER_H

// source1.cpp
#include "header.h"

// Redundant include causing multiple definitions
#include "header.h"

int main() {
  ...
}

// source2.cpp
#include "header.h"

...
Copy after login

Even with include guards, the linker will complain about multiple definitions of f(). The solution is to define the function in only one translation unit or use the inline keyword to instruct the compiler to inline the function body at each call site.

The above is the detailed content of How Do Include Guards Handle Mutual Recursion and Multiple Symbol 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template