modulitos
modulitos

Reputation: 15844

C++: Scoping issues when using a debug variable for a program

I am writing a program where I would like to easily switch on/off my debug code. This program is not production level - it is for a programming competition.

I have only a single file, main.cpp, so I thought a debug variable might be acceptable. I considered the use of a global variable, as follows:

bool DEBUG = true;

int main()
{

    if (DEBUG)
    {
         // print debug statements and other debug code
    }
    // rest of program...

However, I get a warning that my DEBUG variable is never used and if (DEBUG) is always evaluating to false. Alternatively, I can bring my DEBUG variable inside the main() method:

int main()
{
    bool DEBUG = true;
    if (DEBUG)
    {
         // print debug statements and other debug code
    }
    // rest of program...

But then I get a compiler warning 'Condition is always true. Any suggestions on how to easily switch on/off myDEBUG` code? An explanation for the compiler issues would be great.

Upvotes: 0

Views: 132

Answers (2)

utnapistim
utnapistim

Reputation: 27375

[...] I would like to easily switch on/off my debug code [...] Any suggestions on how to easily switch on/off myDEBUG` code?

Consider this:

bool debug = false; // set default value on compilation
int main(int argc, char **argv)
{
    using std::literals::string_literals;

    std::vector<std::string> args{ argv, argv + argc };
    if(std::end(args) != std::find(std::begin(args), std::end(args), "-d"s))
        debug = true; // reset debug flag based on runtime parameter
    // use debug from this point onwards
}

Usage:

$ ./your-app # run with compiled flag
$ ./your-app -d # run with debug information

Notes:

  • The "-d"s construct requires using std::literals::string_literals;.
  • You could set the default debug flag based on a compilation macro (DEBUG, _DEBUG and NDEBUG are the most common on Windows)
  • Consider using boost::program-options if you want more complex parameters handling.

Upvotes: 0

user245019
user245019

Reputation:

Common way is to use the pre-processor

#ifndef NDEBUG
// debug code
#endif

// or

#ifdef DEBUG
// debug code
#endif

Although one project I worked on NDEBUG was undef'd and replaced with another one so check that it exists.

I wouldn't also be surprised that your warning is because there is also a #define DEBUG already present. so your variable DEBUG is never used.

Usually DEBUG and NDEBUG are defined by the compiler.

Upvotes: 1

Related Questions