Override macro from the command line

后端 未结 3 1564
猫巷女王i
猫巷女王i 2021-01-04 12:50

I would like to override a macro from the command line. Somewhere in my source, there is a definition like this:

#define MY_FOO 1

What I wo

相关标签:
3条回答
  • 2021-01-04 13:19

    If you are trying to make something that is configurable from the command line, and you can change the source code, then you can use #ifndef to define the macro only if it is not already defined. So when you define the macro, the code will see it and not overwrite it, but if you don't define it it will have a default value.

    0 讨论(0)
  • 2021-01-04 13:38

    You can't.

    The command line is handled before any source and header files.
    If a source file defines a macro, then it must not be defined before, and will get the new value from now on.
    The only way to change it, is to #undef and #define it again, at a later point. If you have access to a header that is included after the definition, then you have a chance.

    0 讨论(0)
  • 2021-01-04 13:40

    If the file config.h prevents multiple inclusions (via #ifndef CONFIG_H etc), then you could abuse that:

    g++ -DMY_FOO=2 -DCONFIG_H
    

    Note: If the file config.h contains anything else that you need, then you have to define that yourself again as well. You could make a copy of the file as my_config.h and include that. (See also the -include file preprocessor option).

    0 讨论(0)
提交回复
热议问题