參考1:Qt SDK手冊(cè)的Using Precompiled Headers一節(jié);
預(yù)編譯就是編譯一部分代碼編譯為一個(gè)穩(wěn)定的二進(jìn)制文件。在編譯其余代碼的時(shí)候,編譯器會(huì)加載已經(jīng)保存該二進(jìn)制文件。編譯余下代碼的時(shí)候不需要重復(fù)編譯預(yù)編譯文件,這樣就加快的編譯過(guò)程。
- nmake
- Dsp projects (VC 6.0)
- Vcproj projects (VC 7.0 & 7.1)
- Mac OS X
- Unix
1 在工程中添加預(yù)編譯文件
1.1 預(yù)編譯文件的內(nèi)容
預(yù)編譯最好包含穩(wěn)定的不易改變的代碼,一個(gè)典型的預(yù)編譯文件結(jié)構(gòu)如下:
Example: stable.h
//Add C includes here
#if defined __cplusplus
// Add C++ includes here
#include <stdlib>
#include <iostream>
#include <vector>
#include <QApplication> // Qt includes
#include <QPushButton>
#include <QLabel>
#include"thirdparty/include/libmain.h"
#include "my_stable_class.h"
...
#endif
請(qǐng)注意:該預(yù)編譯頭文件必須區(qū)分包含的C文件和C++文件,因?yàn)榘珻文件的預(yù)編譯文件不能包含C++文件。
1.2 工程選項(xiàng)
要使工程使用你的預(yù)處理文件,你需要加上如下的語(yǔ)句
- PRECOMPILED_HEADER = stable.h
qmake會(huì)做其余的工作。你不需要將stable.h包含到HEADERS中,因?yàn)楫?dāng)配置支持PCH的時(shí)候,qmake會(huì)自動(dòng)幫你包含的該文件的。
所有的平臺(tái)都支持預(yù)編譯文件選項(xiàng)precompile_header,你可以使用該選項(xiàng)來(lái)?xiàng)l件定義宏USING_PCH,代碼如下:
- precompile_header:!isEmpty(PRECOMPILED_HEADER) {
- DEFINES += USING_PCH
- }
2. 可能出現(xiàn)的問(wèn)題
在某些平臺(tái),預(yù)編譯的文件后綴名很可能和其他文件名稱相同。例如,下面的代碼可能會(huì)生成相同的中間文件。
- PRECOMPILED_HEADER = window.h
- SOURCES = window.cpp
為了避免這些,最好就是給預(yù)編譯頭文件一個(gè)獨(dú)一無(wú)二的名稱。
/////////////////////////////////////////////////////
// 這部分我沒(méi)使用文檔里面的例子,那個(gè)還不夠簡(jiǎn)單,我這個(gè)更簡(jiǎn)單易懂。
3. 例子代碼
- stable.h
- #ifndef STABLE_H
- #define STABLE_H
-
- /* Add C includes here */
-
- #if defined __cplusplus
- /* Add C++ includes here */
- #include <QWidget>
- #endif
-
- #endif // STABLE_H
- widget.h
- #ifndef WIDGET_H
- #define WIDGET_H
-
- <pre name="code" class="cpp">//#include <QWidget></pre><p></p>
- <pre></pre>
- <pre name="code" class="cpp">// 我這里故意將該句注釋,倘若你添加預(yù)編譯文件stable.h,肯定會(huì)出現(xiàn)</pre><pre name="code" class="cpp">錯(cuò)誤:C2504: 'QWidget' : base class undefined</pre><pre name="code" class="cpp">namespace Ui {
- class Widget;
- }
-
- class Widget : public QWidget
- {
- Q_OBJECT
-
- public:
- explicit Widget(QWidget *parent = 0);
- ~Widget();
-
- private:
- Ui::Widget *ui;
- };
-
- #endif // WIDGET_H</pre><br>
- 下面是<pre name="code" class="cpp">widget.cpp
-
- #include "widget.h"
- #include "ui_widget.h"
-
- Widget::Widget(QWidget *parent) :
- QWidget(parent),
- ui(new Ui::Widget)
- {
- ui->setupUi(this);
- }
-
- Widget::~Widget()
- {
- delete ui;
- }</pre>最后是
- <p></p>
- <p></p><pre name="code" class="cpp">main.cpp
-
- #include "widget.h"
- #include <QApplication>
-
- int main(int argc, char *argv[])
- {
- QApplication a(argc, argv);
- Widget w;
- w.show();
-
- return a.exec();
- }</pre><br>
- <br>
- <p></p>
- <p><br>
- </p>
- <p><br>
- </p>
- <p> </p>
- <p> </p>
- <p> </p>
- <p> </p>
- <p> </p>
- <p> </p>
- <p> </p>
- <p> </p>
- <p> </p>
- <p> </p>
- <p> </p>
- <p> </p>
- <p> </p>
- <p> </p>
- <p> </p>
- <p> </p>
- <p> </p>
- <p> </p>
- <p> </p>
- <p> </p>
- <p> </p>
- <p> </p>
-