[转]Moc的三种用法

(原文地址:https://code.google.com/p/qextserialport/wiki/Three_Usage_Of_MOC)
Three_Usage_Of_MOC
Updated Jan 30, 2013 by dbzhang...@gmail.com
All the developers of Qt should have been familiar with normal usage of MOC.

How to use moc(1)
Consider that we have a Qt project, which contains a subclass of QObject, and the definition of the class is in a header file.
// myclass.h
class MyClass : public QObject
{
Q_OBJECT
public:
MyClass();
};
When qmake is running, once it find macro Q_OBJECT in header file, it will call moc for us.
moc myclass.h -o moc_myclass.cpp
As moc_myclass.cpp is a compile unit, so qmake will run compiler to compile it, then link the moc_myclass.o(bj) to other part. All of them are transparent for users.
g++ moc_myclass.cpp -o moc_myclass.o
How to use moc(2)
What will happen if the definition of the class located in one .cpp source file?
// main.cpp
class MyClass : public QObject
{
Q_OBJECT
public:
MyClass(){}
};

int main(int argc, char**argv)
{
...
}
When qmake is running, once it find macro Q_OBJECT in source file, it will call moc for us too.
moc main.cpp -o main.moc
Then what's the difference?
main.moc is not a compile unit any, as it will dependent on the definition of class MyClass.So it can not include the file "main.cpp".
# This will fail ....
g++ main.moc -o main_moc.o
How to solve this?
//Add following line to main.cpp file, after the definition of MyClass
#include "main.moc"
How to use moc(3)
If you have read the source code of qextserialport, you will find that

QextSerialPort defined in the header file qextserialport.h
But qextserialport.cpp contains following line
#include "moc_qextserialport.cpp"
So, when qmake is running, once it find macro Q_OBJECT in header file, it will call moc for us.
moc myclass.h -o moc_myclass.cpp
But, why we include "moc_qextserialport.cpp" manully?
In order to move private data member and private slots to non-public files, d-pointer and Q_PRIVATE_SLOT are used.

So the generated moc_qextserialport.cpp is dependent on non-public files will make it can not be compiled as a compile unit.

# This doesn't work any more ;-)
g++ moc_qextserialport.cpp -o moc_qextserialport.o
why both moc_xxx.cpp and xxx.moc exist?
In same cases, both myclass.h and myclass.cpp may have Q_OBJECT

// myclass.h
class MyClass : public QObject
{
Q_OBJECT
public:
MyClass();
};
// myclass.cpp
class MyClassHelper : public QObject
{
Q_OBJECT
public:
MyClassHelper();
};

MyClass::MyClass()
{
}
...
In such cases, moc will generated two files for us

moc myclass.h -o moc_myclass.cpp
moc myclass.cpp -o myclass.moc
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值