Why is important to include “.moc” file at end of a Qt Source code file?

怎甘沉沦 提交于 2019-11-27 02:09:50

It's necessary if you define QObject subclasses with the Q_OBJECT macro in a .cpp file. When you do so:

  1. qmake must generate rules inside your Makefile to invoke moc on that .cpp file.

    That special (hackish?) inclusion triggers qmake to do so, and tells it which would be moc's output file (teststring.moc) when invoked on your .cpp.

  2. 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 as YourClass::staticMetaObject and similar, because it has no idea that YourClass 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 means moc's output can be happily compiled.

    But what if your class definition is inside a .cpp? You can't #include a .cpp file in moc'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 means qmake will only emit one rule saying to run moc, but not another rule telling the compiler to compile moc's output.)

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!