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

后端 未结 5 1049
我寻月下人不归
我寻月下人不归 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:18

    You can not use incomplete types, but you can just forward declare them. You just tell the compiler:"Don't get syntax errors, I know what i am doing". Which means that the linker will go and find complete types from libraries whatsoever.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-04 03:28

    You need to forward declare the definitions you need. So if A uses B as a parameter value, you need to forward declare B, and vice versa.

    It could be that just forward declaring the class names:

     class A;
     class B;
    

    solves your problems.

    The accepted answer to this question provides some additional guidance.

    0 讨论(0)
  • 2020-12-04 03:35

    It depends on what is needed from each other's header file. IF it's a class definition, but it only is using a pointer to the class, then instead of including the head file just put in a forward declaration like:

    class MyClassA;

    0 讨论(0)
  • 2020-12-04 03:42

    The solution for this issue is 'forward declaration'.

    If you have a class or a function that needs to be used in 2 headers one of the headers needs to forward declare the used class or type. Or you need to consider to restructure your headers.

    This is a common beginner issue that circular dependencies are causing such issues. If you google on 'forward declaration' will find tons of results.

    Since your question was too unspecific I can't give you an exact answer, sorry for this.

    0 讨论(0)
提交回复
热议问题