Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define value for C++ preprocessor directives during compile time?

Suppose I have a following code:

int main() {

#ifdef NEWMETHOD
    val = new_method("hello world!");
#else
    val = old_method("hello world!");
#endif

    return 0;
}

How can I define NEWMETHOD during compile time?

like image 529
Kintarō Avatar asked Sep 06 '25 03:09

Kintarō


2 Answers

You can either

  • Define it by inserting

    #define NEWMETHOD
    

    into the source code before using it or

  • Add -DNEWMETHOD to your compiler call (works with all popular compilers including GCC, clang and MSVC).

    Depending on your build system you might want to add that to the CFLAGS (C) or CXXFLAGS (C++) environment variables.

like image 172
Martin Konrad Avatar answered Sep 07 '25 23:09

Martin Konrad


You just need to write

#define NEWMETHOD

before you do the #ifdef check.

Of course, then you wouldn't need to write the #ifdef in the first place.

If you want to define the macro without changing the source code, you can pass it in during compilation with the -D flag, like this:

g++ -DNEWMETHOD main.cpp

Obviously, replace the specific compiler command, and file name.

like image 35
cigien Avatar answered Sep 07 '25 21:09

cigien