Search code examples
c++compilationmacrosprecompile

Exclude line from compilation via Makro C++


I've got some problem, which might be simple to solve.

I have code like this:

#define _MG_ALL //This might be defined in some other headerfile

#ifndef _MG_ALL
#define MG_ALL <?????>
#else
#define MG_ALL <nothing>
#endif

In the code it is used like this:

ALL foo = thisIsSomeFunc(foo);

This line should only be compiled, if _ALL is defined. This could also be solved by using this:

#ifdef ALL
    foo = thisIsSomeFunc(int foo);
#endif

But I would prefer just one short macro in the same line.


Solution

  • What you could do is defining the macro like so:

    #ifdef _ALL
    #define ALL if(1)
    #else
    #define ALL if(0)
    #endif
    

    When you use it this it will produce code similar to this

    ALL std::cout << "Debug Message" << std::endl;
     ==> if(1) std::cout << "Debug Message" << std::endl;
    

    A good compiler should recognize the constant value in the if-statement and should only compile the right part (1 ==> if part, 0 ==> nothing).