Header includes in implementation file is causing errors in Qt moc

Header includes in implementation file is causing errors in Qt moc

Problem Description:

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?


#include "foo.h"


#pragma once

class foo {};


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


#pragma once

#include <QtCore>

class bar : public QObject

    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.

Solution – 1

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.


"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>).

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.