Why is important to include ".moc" file at end of a Qt Source code file?
Make an addition:
When Q_OBJECT
in xxx.h, after qmake
, the system will generate a moc_xxx.cpp
with xxx.h in it.
When Q_OBJECT
in xxx.cpp, after qmake
, the system will generate a xxx.moc
, and you need to add the .moc file into the .cpp file.
It's necessary if you define QObject
subclasses with the Q_OBJECT
macro in a .cpp
file. When you do so:
qmake
must generate rules inside yourMakefile
to invokemoc
on that.cpp
file.That special (hackish?) inclusion triggers
qmake
to do so, and tells it which would bemoc
's output file (teststring.moc
) when invoked on your.cpp
.In order to compile
moc
's output (which is still a bunch of C++ code) the compiler must see your class definition. Otherwise, it will complain that there's no such thing asYourClass::staticMetaObject
and similar, because it has no idea thatYourClass
exists.Typically one defines classes featuring
Q_OBJECT
in a header file.moc
then adds a#include "header.h"
into its generated output, and this meansmoc
's output can be happily compiled.But what if your class definition is inside a
.cpp
? You can't#include
a.cpp
file inmoc
's output, as that would give you tons of redefinition errors.Instead, you
#include
moc
's output in your.cpp
, so that it gets compiled together and everyone is happy. (This meansqmake
will only emit one rule saying to runmoc
, but not another rule telling the compiler to compilemoc
's output.)
From 2. you can also also desume that defining classes with Q_OBJECT
in a .h
does not require any special inclusion.