为什么在Qt的源文件中需要包含.moc文件

Question

Why is it important to add an include for .moc file in a Qt cpp source code?

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.

Thanks.

Answer

It’s necessary if you define QObject subclasses with the Q_OBJECT(对,它是宏) macro in a .cpp file. When you do so:

qmake must generate rules inside your Makefile to invoke(调用) moc(元对象编译器,进行预处理过程) on that .cpp file.

That special (hackish(有极客特征的,开拓性的)?) inclusion triggers qmake to do so(指包含.moc文件会触发上述的事情), and tells it which would be moc’s output file (teststring.moc) when invoked on your .cpp.

In order to compile moc’s output (which is still a bunch of C++ code) the compiler must see your class definition(意思是想要编译.moc文件,需要知道在.cpp文件中的类的定义.那直接把cpp包含到.moc中,会报错的,下面会提到). Otherwise, it will complain that there’s no such thing as YourClass::staticMetaObject and similar, because it has no idea that YourClass exists.

我发现,当在.cpp中不去include .moc文件时,报错内容为"undefined reference to 'vtable for YourClass'''".并未报上述描述中说的.

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.(当Q_OBJECT 定义在.h中,.moc文件中会自动加上这个.h文件,则类的定义直接就拿到了)

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.(但是你不能直接把.cpp文件加到.moc文件中,它会报重定义的问题. -> 如果.cpp中include .moc文件, .moc文件中includecpp文件这样会报重定义.但如果cpp中不包含.moc文件,还是报""undefined reference to ‘vtable for YourClass’’’"这样的错误).

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.在这种情况下qmake不再单独去编译.moc文件了)

From 2. you can also also desume(唤醒) that defining classes with Q_OBJECT in a .h does not require any special inclusion.

参考文章:
Why is it important to add an include for .moc file in a Qt cpp source code?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值