使用qmake的预处理选项进行条件编译

问题引入

在使用qmake构建项目时,经常有不同的预处理选项,需要在预处理期间将代码区分开。另外还有一些情况下需要在编译时使用不同的编译选项将待编译的文件区分开。看下面一个例子。

该项目下包含:aaa.h、aaa.cpp、bbb.h、bbb.cpp、main.cpp五个文件,内容分别如下:

aaa.h

1 #ifndef AAA_H_
2 #define AAA_H_
3 
4 void test(int val);
5 
6 #endif

aaa.cpp

1 #include "aaa.h"
2 #include <iostream>
3 
4 void test(int val)
5 {
6     std::cout << "AAA::test " << val << std::endl;
7 }

bbb.h

#ifndef BBB_H_
#define BBB_H_

void test(int val);

#endif

bbb.cpp

1 #include "bbb.h"
2 #include <iostream>
3 
4 void test(int val)
5 {
6     std::cout << "BBB::test " << val << std::endl;
7 }

main.cpp

 1 #include <iostream>
 2 
 3 #ifdef USE_AAA
 4 #include "aaa.h"
 5 #else
 6 #include "bbb.h" 
 7 #endif
 8 
 9 int main(int argc, char* argv[])
10 {
11 #ifdef USE_AAA
12     std::cout << "USE_AAA" << std::endl;
13     test(123);
14 #else
15     std::cout << "NO USE_AAA" << std::endl;
16     test(123);
17 #endif
18 }

解决方案

现在想要通过在编译时指定USE_AAA实现不同选项的区别编译。因此,可以这样写pro文件:

 1 TEMPLATE = app
 2 TARGET = testpro
 3 INCLUDEPATH += .
 4 
 5 DEFINES += QT_DEPRECATED_WARNINGS
 6 
 7 #HEADERS += 
 8 #           aaa.h 
 9 #           bbb.h
10 
11 if(contains(DEFINES, USE_AAA)) {
12 HEADERS += aaa.h
13 }else{
14 HEADERS += bbb.h
15 }
16 
17 SOURCES += 
18 #           aaa.cpp 
19 #           bbb.cpp 
20            main.cpp
21 
22 if(contains(DEFINES, USE_AAA)) {
23 SOURCES += aaa.cpp
24 }else{
25 SOURCES += bbb.cpp
26 }

直接使用qmake构建项目

qmake

运行结果如下

NO USE_AAA
BBB::test 123

使用编译选项

qmake DEFINES+=USE_AAA

运行结果如下:

USE_AAA
AAA::test 123

总结

使用DEFINES选项可以达到效果,感兴趣的可以观察两种情况下Makefile的区别。另外,需特别注意pro文件中条件语句的写法,左花括号需要与条件语句位于同一行,这个切忌不要搞错了。

原文地址:https://www.cnblogs.com/nuoforever/p/13997311.html