Circular dependencies with headers. Using #ifndef and #define

后端 未结 3 1612
后悔当初
后悔当初 2021-01-16 03:55

I have the very simple following code:

main.cpp

#include \"ui_library_browser.h\"
#include 
#include \"StartWindow.h\"
int          


        
相关标签:
3条回答
  • Do you use StartWindow in MainWindow? If not, simply remove the StartWindow.h include. Otherwise make the main_window a pointer instead of a variable.

    0 讨论(0)
  • 2021-01-16 04:43

    So called "header guards" are used to prevent a bit different kind of error: including same header multiple time through different indirect inclusions in one compile unit. For example, you include "a.h" from main.cpp and then include "b.h" from main.cpp, that includes "a.h" itself somewhere inside.

    In your case two headers try to include each other circurally, that is not possible - C/C++ preprocessor works as simple text "copy-paste" and this case would invent infinite recursion of text insertion.

    And I really don't see why would you need "StartWindow.h" inclusion in "MainWindow.h" header.

    0 讨论(0)
  • 2021-01-16 04:45

    In the file StartWindow.h remove #include "MainWindow.h" and add the forward declaration (before class StartWindow ...):

    class MainWindow;
    

    In the same file change the member MainWindow main_window to

    const MainWindow* main_window; 
    

    or

    const MainWindow& main_window; 
    

    In the latter case you would need to pass const MainWindow& in the constructor of StartWindow.

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