Home >Backend Development >C++ >How Can Circular Header Inclusion Be Avoided in C ?
Headers Including Each Other in C
C header files can include each other, but certain guidelines must be followed to avoid compilation errors.
Include Statement Placement
Forward Declarations
Consider the following code where two classes, A and B, include each other:
<code class="cpp">// A.h #ifndef A_H_ #define A_H_ #include "B.h" class A { public: A() : b(*this) {} private: B b; }; #endif</code>
<code class="cpp">// B.h #ifndef B_H_ #define B_H_ #include "A.h" class B { public: B(A& a) : a(a) {} private: A& a; }; #endif</code>
In this scenario, the compiler encounters class B first, but A has not yet been declared. To resolve this, a forward declaration of A should be included before the definition of B:
<code class="cpp">// B.h #ifndef B_H_ #define B_H_ class A; // Forward declaration of class A #include "A.h" class B { public: B(A& a) : a(a) {} private: A& a; }; #endif</code>
This forward declaration informs the compiler that A is a class, even though its complete definition is not yet available.
In Practice
In general, #include statements should be placed inside include guards, and forward declarations should be used when a header needs to refer to a class that is defined in a later included header. By following these guidelines, you can avoid compilation errors caused by circular includes.
The above is the detailed content of How Can Circular Header Inclusion Be Avoided in C ?. For more information, please follow other related articles on the PHP Chinese website!