Search code examples
cloggingmacrosc-preprocessorconditional-compilation

Trouble with #ifdef across multiple files


util.h contains the following code:

#ifdef DEBUG
#define LOGGER() MACRO_WRAP(printf("Entering %s\n", __func__))
#else
#define LOGGER() MACRO_WRAP()
#endif

foo.c contains this code:

void foo_start(foo *m)
{
    LOGGER();

    do_action(m, START);
}

and then foo_unit_tests.c contains calls to foo_start(). I'd like to be able to #define DEBUG at the top of the relevant files -- i.e. I want it to be turned on for unit tests, but not for the main code.

I can't get it to work. Putting #define DEBUG at the top of foo_unit_tests.c doesn't produce the desired behavior. The only way I can get it to work is by putting #define DEBUG either at the top of util.h or foo.c, both of which are much messier than I would like.

What am I missing here? I thought that the macro defined in the .c file would be visible inside of all of the .h files that it included.


Solution

  • You have to have the #define at the beginning of all your files that need that macro defined, or through including a .h file that has it in it.

    If you want a cleaner way of doing that, then it is probably better to use the compiler flags to set environmental variables.

    For example

    icpc -DDEBUG=whatever source.c ...
    

    Or even better, you can enable this compiler flag though an environmental variable in your makefile.