問題描述
為什么在 Qt cpp 源代碼中為 .moc 文件添加一個包含很重要?
Why is it important to add an include for .moc file in a Qt cpp source code?
這是幾個Qt示例中常用的步驟,包括這個:http://doc.qt.io/qt-5/qttestlib-tutorial1-example.html; 其中行 #include "testqstring.moc"
應該包含在文件的末尾.
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.
推薦答案
如果您在 中使用
文件.這樣做時:Q_OBJECT
宏定義 QObject
子類,則這是必要的.cpp
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 yourMakefile
to invokemoc
on that.cpp
file.
那個特殊的(hackish?)包含會觸發 qmake
這樣做,并告訴它哪個將是 moc
的輸出文件 (teststring.moc
) 在您的 .cpp
上調用時.
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
的輸出(仍然是一堆C++代碼),編譯器必須看到你的類定義.否則,它會抱怨沒有諸如 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
然后在其生成的輸出中添加一個 #include "header.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
中呢?您不能在 moc
的輸出中 #include
一個 .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
moc
的輸出放在.cpp
中,以便將其編譯在一起,每個人都很高興.(這意味著 qmake
只會發出一個規則,說運行 moc
,而不是另一個規則告訴編譯器編譯 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.)
從 2. 您還可以假設在 .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 源代碼文件末尾的文件?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!