How to solve the problem of mutual inclusion of header files in CPP ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

How to solve the problem of mutual inclusion of header files in CPP ?

For example : // A.h #ifndef A_H #define A_H #include "B.h" class A { B b; } #endif //B.h #ifndef B_H #define B_H #include "A.h" class B { A a; } #endif one header requires the others, thus the compiler prints an error that one of the types A or B is undeclared.

20th Aug 2021, 10:26 AM
Abdelhaq El Amraoui
Abdelhaq El Amraoui - avatar
2 Answers
+ 3
I don't think this is possible. If you compile A.h, B.h will be compiled first, which has a member A and at this time it's undefined. Same thing for B. The best you can do is to forward declare class A and B. Though you still can't make it work, this works for pointer and reference types. You can refer to this post: https://stackoverflow.com/questions/8526819/c-header-files-including-each-other-mutually
20th Aug 2021, 3:35 PM
你知道規則,我也是
你知道規則,我也是 - avatar
+ 2
and, also it's unnecessary to add two marcos since you aren't using them anywhere in your code. either, you can remove it or use #pragma once
20th Aug 2021, 4:39 PM
Rellot's screwdriver
Rellot's screwdriver - avatar