Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override macro from the command line

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?

like image 572
Sh4pe Avatar asked Aug 28 '13 08:08

Sh4pe


People also ask

How do you override a macro?

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.

Can I redefine a macro?

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.

How do you define a macro in CMake?

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.


1 Answers

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.

like image 71
ugoren Avatar answered Oct 04 '22 18:10

ugoren