开发者

Circular dependencies with headers. Using #ifndef and #define

I have the very simple following code:

main.cpp

#include "ui_library_browser.h"
#include <QtGui/QApplication>
#include "StartWindow.h"
int main(int argc, char *argv[])
{
  QApplication a(argc, argv);
  StartWindow w;
  w.show();
  return a.exec();
}

StartWindow.h

#ifndef STARTWINDOW_H_
#define STARTWINDOW_H_

#include <qwidget>
#include "MainWindow.h"

class StartWindow : public QWidget
{ 
  Q_OBJECT

public:
  StartWindow();
  ~StartWindow();
  MainWindow main_window;  //<-- Problem
};
#endif

MainWindow.h

#ifndef MAINWINDOW_H_
#define MAINWINDOW_H_

#include <qdialog.h>
#include "StartWindow.h"

class MainWindow : public QDialog
{
  Q_OBJECT

public:
  MainWindow();
  ~MainWindow();
};
#endif

This produces er开发者_运维技巧rors because of the inclusion of #include "StartWindow.h" in the MainWindow.h header. However, I thought the use of #ifndef and #define are to stop problems like this? Can someone clear this up for me?


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.


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜