問題描述
為什么在 Qt cpp 源代碼中為 .moc 文件添加一個(gè)包含很重要?
Why is it important to add an include for .moc file in a Qt cpp source code?
這是幾個(gè)Qt示例中常用的步驟,包括這個(gè):http://doc.qt.io/qt-5/qttestlib-tutorial1-example.html; 其中行 #include "testqstring.moc"
應(yīng)該包含在文件的末尾.
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.
推薦答案
如果您在 中使用
文件.這樣做時(shí):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
中生成規(guī)則以在該.cpp
上調(diào)用moc
> 文件.
qmake
must generate rules inside yourMakefile
to invokemoc
on that.cpp
file.
那個(gè)特殊的(hackish?)包含會(huì)觸發(fā) qmake
這樣做,并告訴它哪個(gè)將是 moc
的輸出文件 (teststring.moc
) 在您的 .cpp
上調(diào)用時(shí).
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++代碼),編譯器必須看到你的類定義.否則,它會(huì)抱怨沒有諸如 YourClass::staticMetaObject
之類的東西,因?yàn)樗恢?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
然后在其生成的輸出中添加一個(gè) #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
一個(gè) .cpp
文件,因?yàn)檫@會(huì)給您帶來大量的重新定義錯(cuò)誤.
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
中,以便將其編譯在一起,每個(gè)人都很高興.(這意味著 qmake
只會(huì)發(fā)出一個(gè)規(guī)則,說運(yùn)行 moc
,而不是另一個(gè)規(guī)則告訴編譯器編譯 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. 您還可以假設(shè)在 .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.
這篇關(guān)于為什么包含“.moc"很重要?Qt 源代碼文件末尾的文件?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!