Proper way to #include when there is a circular dependency?

后端 未结 5 1069
我寻月下人不归
我寻月下人不归 2020-12-04 02:49

I\'m using #pragma once, not #include guards on all my h files. What do I do if a.h needs to #include b.h and b.h needs to #include a.h?

I\'m getting all sorts if e

5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-04 03:27

    One possibility is to refactor some portion of the files a.h and b.h into a third file say c.h, and include it from both a.h and b.h. This way, the latter two would no longer need to mutually include each other.

    Another possibility is to merge the separate header files into one.

    A third possibility is the situation when two classes legitimately need to refer to each other. In such cases you have to use pointers. Moreover, you can forward declare the class instead of including its header file. [Mentioned also by jdv] For example,

    // file a.h
    struct B;
    struct A { B * b_ };
    
    // file b.h
    struct A; 
    struct B { A * a_; };
    

    However, without knowing your particular situation it is difficult to provide specific suggestion.

提交回复
热议问题