为什么包含“.moc"很重要?Qt 源代码文件末尾的

时间:2023-02-02
本文介绍了为什么包含“.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:

  1. qmake 必须在您的 Makefile 中生成规则以在该 .cpp 上调用 moc> 文件.

  1. qmake must generate rules inside your Makefile to invoke moc 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模板网!

上一篇:Qt 中 QWidget 的模糊效果 下一篇:QML 和 C++ 图像互操作性

相关文章

最新文章