简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM