问题描述
为什么在Qt cpp源代码中为.moc文件添加一个include很重要?
Why is important to add an include for .moc file in a Qt cpp source code?
这是在serveral Qt示例中使用的常见步骤, :
;其中行#includetestqstring.moc应该包含在文件的结尾。
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.
谢谢。
推荐答案
如果您定义 QObject 中的 Q_OBJECT 宏。
It's necessary if you define QObject subclasses with the Q_OBJECT macro in a .cpp file. When you do so:
-
qmake 必须在 Makefile 可以在 .cpp 文件中调用 moc 。
qmake must generate rules inside your Makefile to invoke moc on that .cpp file.
这个特殊的(hackish?)包含触发 qmake 这样做,并告诉它 moc $当在 .cpp 上调用时,c $ c>的输出文件( teststring.moc
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.
为了编译 moc 的输出代码)编译器必须看到你的类定义。否则,它会抱怨没有像 YourClass :: staticMetaObject 和类似的东西,因为它不知道 YourClass 存在。
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.
通常在头文件中定义具有 Q_OBJECT 的类。 moc 然后在其生成的输出中添加 #includeheader.h,这意味着 moc 的输出可以很高兴地编译。
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.
但是如果你的类定义在 .cpp 您不能中的 #include a .cpp 文件
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.
而是 #include $ c $在 .cpp 中输出 moc ,以便它编译在一起,每个人都很高兴。 (这意味着 qmake 只会发出一条规则,要求运行 moc ,而不是另一条规则, code> moc 的输出。)
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.)
也不需要在 .h 中定义具有 Q_OBJECT 的类不需要任何特殊的包含。
From 2. you can also also desume that defining classes with Q_OBJECT in a .h does not require any special inclusion.
这篇关于为什么重要的是包括“.moc”文件在Qt源代码文件的末尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!