Home > Net >  Header includes in implementation file is causing errors in Qt moc
Header includes in implementation file is causing errors in Qt moc

Time:12-07

Imagine I have a class foo with a header and an implementation file.

I also have those for bar. However, in bar I have an instance of foo. But I don't include foo in the header of bar but in the implementation file.

Qt's moc does not include the foo header, causing errors for not knowing the existence of the class foo.

Is there a way of keeping the include in the implementation file and having the moc add those includes as well?

foo.cpp

#include "foo.h"

foo.h

#pragma once

class foo {};

bar.cpp

#include "foo.h"
#include "bar.h"

bar.h

#pragma once

#include <QtCore>

class bar : public QObject
{
    Q_OBJECT

public:
    foo instanceOfFoo;
};

The moc will not include foo.h. Which in turn generates errors telling me moc_bar.cpp is unaware of a class named foo.

CodePudding user response:

The short answer is: No, you can't.

The reason is that bar has a foo member. In order to generate the definition of bar, the compiler must know what a foo is. Otherwise the memory layout of bar would be impossible to determine.

So you have to #include "foo.h" in bar.h.

You could circumvent it by using a pointer to foo and a forward declaration but it sounds wrong to me.

Also:

"The principle of keeping includes out of header files [...]"

There is no issue to have #include directives in header files. You only need to include what's necessary for your class to be completely defined (e.g. You need a std::string member ? Just #include <string>).

  •  Tags:  
  • c qt
  • Related