Search code examples
c++preprocessorpreprocessor-directive

How does #define know when to stop looking?


I use a macro in C++ to switch between compiling logging or not:

#define MAYBE_LOG(msg) 
#ifdef PRINT_MSGS 
ALWAYS_LOG(msg) 
#endif

How does the #define know where the ending is? The #endif refers to the #ifdef, not the #define.


Solution

  • The code in the question does two separate things: it defines a macro named MAYBE_LOG with no body and, if PRINT_MSGS is defined, it uses a macro named ALWAYS_LOG. If that's not what it's supposed to do, then, yes, it needs to be changed. Since the question doesn't say what the code is supposed to do, this is just a guess:

    #ifdef PRINT_MSGS
    #define MAYBE_LOG(msg) ALWAYS_LOG(msg)
    #else
    #define MAYBE_LOG(msg)
    #endif
    

    The reason for doing it this way (and not using \ on each line to extend the macro definition is that you can't put #if conditions inside the definition of a macro.