qmoc文件_为什么重要的是包括“.moc”文件在Qt源代码文件的末尾?
Why is important to add an include for .moc file in a Qt cpp source code?This is a common step used in serveral Qt samples, including this one:http://doc.qt.io/qt-5/qttestlib-tutorial1-example.html; w
Why is important to add an include for .moc file in a Qt cpp source code?
This is a common step used in serveral 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 exactaly why this is neccessary.
thanks.
解决方案
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 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.
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.
开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!
更多推荐
所有评论(0)