Why is it important to include the ".moc" file at the end of the Qt source file?

Why is it important to add an include file for .moc in the Qt cpp source code?

This is a common step used in Qt server samples, including this one: http://doc.qt.io/qt-5/qttestlib-tutorial1-example.html ; where the line #include "testqstring.moc" should be included at the end of the file.

I do not understand exactly why this is necessary.

thanks.

+5
source share
1 answer

Required if you are defining QObject subclasses with the Q_OBJECT macro in a .cpp file. . When you do this:

  • qmake must generate rules inside your Makefile to call moc in this .cpp file.

    This special (hacker?) Inclusion starts qmake for this and tells it that the moc will be the output file ( teststring.moc ) when called on your .cpp .

  • To compile the output of moc (which is still a C ++ code binding), the compiler should see your class definition. Otherwise, he will complain that there is no such thing as YourClass::staticMetaObject and the like, because she does not know that YourClass exists.

    Usually classes with Q_OBJECT defined in header files. moc then adds #include "header.h" to its generated output, which means that moc output can be compiled with pleasure.

    But what if your class definition is inside .cpp ? You cannot #include a .cpp in the moc file, as this will give you a ton of override errors.

    Instead, you #include moc in your .cpp so that it compiles together and everyone is happy. (This means that qmake produces only one rule saying to run moc , but not another rule telling the compiler to compile the output of moc .)

From 2. you can also assume that defining classes with Q_OBJECT in .h does not require special inclusion.

+14
source

Source: https://habr.com/ru/post/1241152/


All Articles