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 would like is to set the value of this macro when I compile my program:
g++ -DMY_FOO=2 ...
But then, the macro is redefined by the source code to its old value 1. The problem is that I don't own the part of the source that defines the macro in the first place. If it were my own code, I could simply write
#ifndef MY_FOO
#define MY_FOO 1
#endif
And my problem would be gone. So is there way to specify a macro on the command line using g++ so that the source code cannot redefine it?
Answer: To override an existing macro, we need to undefine existing macro using “#undef”. Then, we need to define same macro again with new value.
Redefining a macro is simply using the #define directive to provide a new macro body for an existing macro definition. If the redefinition is identical to the original definition, the compiler goes on without emitting any type of diagnostic message.
If you are using CMake 3. X your first choice for adding a preprocessor macro should be target_compile_definitions. The reason you should prefer this approach over any other approach is because it granularity is target based. IE the macro will only be added to your exe/library.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With