关于C/C /QT中的条件构建(宏)

Regarding conditional build (Macro) in C/C++/QT

本文关键字:构建 QT 关于 条件      更新时间:2023-10-16

我想知道在我进行有条件构建的常见(推荐)方法以选择要构建的方法。


因此,可以选择两个文件。

条件1:

class Page : QWebPage {
    public:
        string test1;
}

条件2:

class EnginePage : QWebEnginePage {
    public:
        string test1;
        string test2;
}

我看到的最常见的方法是使用与Makefile相关的文件类似:

与Makefile有关的文件:

Source     += 
               one.h 
               two.h 
               three.h 
               four.h 
#if (one_defined)
    Source  += Page.h
#else
    Source  += EnginePage.h
#end


但是(这是问题)我想知道与此相似(使用一个文件而不是两个文件)是可能的,并且建议:

单个文件(条件1 条件2):

#if (one_defined)
    class Page : QWebPage
#else 
    class EnginePage : QWebEnginePage {
#endif
    public:
        string test1;
#if (one_defined)
        string test2;
#endif
}

您可以在.h文件中使用#cmakedefine CMAKE_VAR

CONFIGURE_FILE将自动替换为#define CMAKE_VAR/* #undef CMAKE_VAR*/取决于CMAKE_VAR是否设置在CMAKE中。

一个具体示例:

假设您有一个CMAKE变量,该变量称为QWebPage_Defined,如果定义了qwebpage,则等于true。

您将需要创建一个包含:

的文件(例如configure.h.in
#cmakedefine QWebPage_Defined

在您的cmake脚本中,您将调用CONFIGURE_FILE函数:

configure_file("configure.h.in", "${CMAKE_BINARY_DIR}/configure.h")

然后在您的标题中:

#include "configure.h" // Include the file
#ifdef QWebPage_Defined // Warning : use #ifdef and not #if
    class Page : QWebPage
#else 
    class EnginePage : QWebEnginePage {
#endif
    public:
        string test1;
#ifdef QWebPage_Defined // Warning : use #ifdef and not #if
        string test2;
#endif
}