简体   繁体   English

如何在编译期间定义 C++ 预处理器指令的值?

[英]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?如何在编译时定义 NEWMETHOD?

You just need to write你只需要写

#define NEWMETHOD

before you do the #ifdef check.在进行#ifdef检查之前。

Of course, then you wouldn't need to write the #ifdef in the first place.当然,那么您一开始就不需要编写#ifdef

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:如果要在不更改源代码的情况下定义宏,可以在编译期间使用-D标志将其传入,如下所示:

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).-DNEWMETHOD添加到您的编译器调用(适用于所有流行的编译器,包括 GCC、clang 和 MSVC)。

    Depending on your build system you might want to add that to the CFLAGS (C) or CXXFLAGS (C++) environment variables.根据您的构建系统,您可能希望将其添加到CFLAGS (C) 或CXXFLAGS (C++) 环境变量中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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