Why is it important to add an include for .moc file in a Qt cpp source code?
This is a common step used in several Qt samples, including this one: http://doc.qt.io/qt-5/qttestlib-tutorial1-example.html; where the line #include "testqstring.moc" should be included in the end of the file.
I don't understand exactly why this is necessary.
Thanks.
It's necessary if you define QObject subclasses with the Q_OBJECT macro in a .cpp file. When you do so:
qmakemust generate rules inside yourMakefileto invokemocon that.cppfile.That special (hackish?) inclusion triggers
qmaketo 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::staticMetaObjectand similar, because it has no idea thatYourClassexists.Typically one defines classes featuring
Q_OBJECTin a header file.mocthen 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#includea.cppfile inmoc's output, as that would give you tons of redefinition errors.Instead, you
#includemoc's output in your.cpp, so that it gets compiled together and everyone is happy. (This meansqmakewill 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.
来源:https://stackoverflow.com/questions/34928933/why-is-important-to-include-moc-file-at-end-of-a-qt-source-code-file