Search code examples
makefileg++conditional-compilation

Can flags defined in Makefile using '-D' be used within header files?


I noticed that a flag I defined as -D__SOME_FLAG=1 on the compile line(g++), when used in a header file, did not seem to have the desired affect. ie: code that was enclosed within a #ifdef __SOME_FLAG ... #endif, did not seem to be compiled. I can always use a #define within the headers, to make this work. But ideally , I want to be able to make a change in one place(ie: the Makefile).

I wanted to know if what I am trying is possible?

thanks


Solution

  • Yes, it should be possible and the -D flag is exactly for that.

    Please check http://gcc.gnu.org/onlinedocs/gcc/Preprocessor-Options.html#Preprocessor-Options

    From what I read there, maybe you should use -D symbol=value with a space between them, or -D"symbol=value" with quotes.. I didn't try however as my laptop's battery is currently dying:)

    edit:
    Sorry, just remembered that on linuxes there should be no space, so your commandline with -D__SOME_FLAG=1 should be correctly setting "__SOME_FLAG" to 1. If you are not on linux but windows, you caould try with space, but I doubt. Also, if the GCC is old or funky, it may actually ignore the first character after -D and so a "_SOME_FLAG" could be defined instead. I've seen it a few times but only on some very buggy ports..

    btw. Maybe something other #undefs it? Or maybe you have forgotten to add that flag to all compilations of all files? -D options are used only on the file(s) currently compiled, so if you have a several gcc invocations in your Makefile, you might have added the flag only to some of them. That was usually my issue, as I tend to put the -I and -D flags only on first, and forget about the other modules..