Cannot compile MOC file if Q_OBJECT macro is removed by other macro: The header file doesn't include <QObject>

StackOverflow https://stackoverflow.com/questions/10374476

  •  04-06-2021
  •  | 
  •  

Question

When compiling a non-Qt version of a Qt/C++ program (-DDISABLE_MYMODULE), I get this compiler error:

src/mymodule.moc.cpp:12:2: error: #error "The header file
'mymodule.hpp' doesn't include <QObject>."
src/mymodule.moc.cpp:19:1: error: ‘QT_BEGIN_MOC_NAMESPACE’ does not name a type
src/mymodule.moc.cpp:40:6: error: ‘MyModule’ has not been declared
...

I'm using GNU make (not qmake). My Makefile compiles two object files per module, one directly from the .cpp source file and the MOC object file from the .moc.cpp source file (this is what doesn't work), both using g++. This .moc.cpp source file is created by MOC, from the .hpp header (this process does not throw an error).

The header file in question looks somewhat like this:

#ifndef DISABLE_MYMODULE //My problem macro
#ifndef MYMODULE_HPP
#define MYMODULE_HPP
//...
class MyModule : //...
{
    Q_OBJECT //Qt problem macro
    //...
};
//...
#endif
#endif

The whole thing will compile (and later link, execute) just fine if don't set my problem macro. If I do set it, but comment out QT's problem macro, it'll compile fine as well (building a non-Qt version).

I don't exactly know, what MOC replaces Q_OBJECT by, but shouldn't it still be inside my DISABLE_MYMODULE and therefore be removed by the preprocessor?

Was it helpful?

Solution

It looks like with your macro DISABLE_MYMODULE you exclude class definition, which includes Q_OBJECT. On the other hand, this code still processed by moc tool, which generates your mymodule.moc.cpp file, which in turn includes your mymodule.hpp header file. When mymodule.moc.cpp is then processed by compiler it includes .hpp file, but preprocessor excludes its content because of DISABLE_MYMODULE, so compiler do not find definition of the class, #include <QObject> and things to which Q_OBJECT macro should be expanded. So compiler do not find the things, which it expects to be and becom upset...

I think, the solution will be to exclude mymodule.moc.cpp from build if DISABLE_MYMODULE is defined or (better) disable moc processing on mymodule.hpp, if DISABLE_MYMODULE is defined.

OTHER TIPS

Try to check next criterias:

  1. Class should be inherit from QObject directly or indirectly, and QObject must be first in the inheritance list.
  2. Class is defined and implemented in separate *.h and *.cpp files. If not, you need to add #include "you_cpp_file.moc" to end of the file where class is implemented and defined.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top