Why is important to include quot;.mocquot; file at end of a Qt Source code file?(为什么包含“.moc很重要?Qt 源代码文件末尾的文件?)
问题描述
为什么在 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> 文件.
qmakemust generate rules inside yourMakefileto invokemocon that.cppfile.
那个特殊的(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 源代码文件末尾的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么包含“.moc"很重要?Qt 源代码文件末尾的
基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 常量变量在标题中不起作用 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 这个宏可以转换成函数吗? 2022-01-01
