Sean83
Sean83

Reputation: 493

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

I would like to know the common (recommended) way to select which to build when I do a conditional build.


So For example, there are two files that could be selected.

Condition 1:

class Page : QWebPage {
    public:
        string test1;
}

Condition 2:

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

The most common way that I saw is using makefile-related file similar to below:

File related to Makefile:

Source     += \
               one.h \
               two.h \
               three.h \
               four.h \

#if (one_defined)
    Source  += Page.h
#else
    Source  += EnginePage.h
#end


but (Here is the Question) I would like to know whether similar to this (using one single file instead of two) is possible and recommended:

Single file (Condition 1 + Condition 2):

#if (one_defined)
    class Page : QWebPage
#else 
    class EnginePage : QWebEnginePage {
#endif

    public:
        string test1;

#if (one_defined)
        string test2;
#endif
}

Upvotes: 1

Views: 83

Answers (1)

Blabdouze
Blabdouze

Reputation: 1121

You can use #cmakedefine CMAKE_VAR in a .h file.

CONFIGURE_FILE will automatically replace it by #define CMAKE_VAR or /* #undef CMAKE_VAR*/ depending on whether CMAKE_VAR is set in CMake or not.

A concrete example :

Let's say you have a CMake variable that is called QWebPage_Defined that is equal to true if QWebPage is defined.

You'll have then to create a file (e.g. configure.h.in) that contains :

#cmakedefine QWebPage_Defined

In your CMake script you will call the CONFIGURE_FILE function :

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

And then in your header :

#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
}

Upvotes: 1

Related Questions