Home > Net >  Removing code in Release mode using macros C
Removing code in Release mode using macros C

Time:10-27

I have some code that is used for debugging and don't want then to be in the releases.
Can I use macros to comment them out?
For example:

#include <iostream>

#define p(OwO) std::cout << OwO
#define DEBUG 1    // <---- set this to -1 in release mode

#if DEBUG == 1
#define DBUGstart
#define DBUGend
// ^ is empty when in release mode
#else
#define DBUGstart /*
#define DBUGend    */
/*
IDE(and every other text editor, including Stack overflow) comments the above piece of code,
problem with testing this is my project takes a long
time to build
*/
#endif

int main() {
    DBUGstart;
    p("<--------------DEBUG------------->\n");
    // basically commenting this line in release mode, therefore, removing it
    p("DEBUG 2\n");
    p("DEBUG 3\n");
    DBUGend;
    p("Hewwo World\n");
    return 0x45;
}

For single line debugs I could easily do something like:

#include <iostream>

#define DEBUG -1  // in release mode
#define p(OwO) std::cout << OwO

#if DEBUG == 1
#define DB(line) line
#else
#define DB(line)
#endif

int main()
{
    DB(p("Debug\n"));
    p("Hewwo World");
    return 0x45;
}

But I guess this will be a bit messy with multiple lines

I'm working with MSVC (Visual Studio 2019), if this doesn't work then is there any other way of implementing the same (for multi lines, it's pretty simple for the single lines)?

CodePudding user response:

You are making this unnecessarily complicated.

Instead of conditionally inserting C-style comments if in Release, just only insert the code if in Debug. Visual Studio defines _DEBUG by default in Debug configurations, so you can use this like the following:

#include <iostream>

int main() {

    std::cout << "hello there. \n";

#ifdef _DEBUG
    std::cout << "this is a debug build.";
#endif

}

CodePudding user response:

You don't even need macros for this. Conditional compilation is baked right into the language:

#include <iostream>

constexpr bool gDebug = true;

int foo();

int main() {

    std::cout << "hello there.\n";

    int foo_res = foo();

    if constexpr (gDebug) {
       std::cout << "Foo returned: " << foo_res << "\n";
    }
}

This has the immediate benefit of still checking that the code is valid even when it is compiled out.

It also cleanly handles variables that are only needed in debug, which commonly cause release-only warning messages when using macro-based conditional compilation.

  • Related