11

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?

5
  • 1
    Why do you want to do this? There may be another way if you tell us the real problem
    – doctorlove
    Aug 28, 2013 at 8:44
  • 3
    Do you need it to have your definition within the header file itself, or would it work to simply #undef it after your #include?
    – svk
    Aug 28, 2013 at 8:45
  • The real problem is that I'm working on a project where the debug level of several output streams is set using config.h, which is in turn generated by the autotools. But I only want to compile one simple test program in my package with a higher debug level and I do not want to reconfigure the whole package, because this takes quite some time.
    – Sh4pe
    Aug 28, 2013 at 8:46
  • @svk This might be a good idea, I'll have a look... Would be nice to have an answer to my original question though :)
    – Sh4pe
    Aug 28, 2013 at 8:48
  • 2
    @Sh4pe I would guess that the answer to your original question is probably "no".
    – svk
    Aug 28, 2013 at 9:05

3 Answers 3

11

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

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

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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.