简体   繁体   中英

How to view the output of DEBUG conditional statement?

I have written a code with #ifdef DEBUG conditional statement to print cout statement in code blocks. My questions are:

  1. so these conditional Debug will appear only during condition right?
  2. if so how do I view the output in code blocks when I debug the code?

I am not sure about codeblocks but in visual studio you can select if you want to build the debug or release version of the program (or any other version you define). What this effectively does is that it will set the flag DEBUG to true. and you don't need to define a variable manually. In any case you can use your own definition for this.

In the debug version anything inside the #ifdef DEBUG will be also compiled while in the release version these chunks of code will be skipped. To get information from debugging you can define a macro debug print like this.

#define DEBUG_MODE 1 // Or 0 if you dont want to debug

#ifdef DEBUG_MODE
#define Debug( x ) std::cout << x
#else
#define Debug( x ) 
#endif

and then call your Debug( someVariable ); If you build the debug version you get output in the console otherwise nothing will happen.

As mentioned in other comments/answers you can define a macro such as DEBUG(message) for printing debug messages in debug builds only. However, I suggest you use NDEBUG instead of DEBUG to do so. NDEBUG is a standardized predefined macro that is automatically defined by compiler in release build, if this is your intent. Use it this way :

// #define NDEBUG  ==> not needed, this macro will be predefined by compiler in release build

#ifdef NDEBUG         // release build
# define DEBUG(msg)
#else                 // debug build
# define DEBUG(msg)   std::cout << msg
#endif

int main(void)
{
    DEBUG("this will be printed to console in debug build only\n");
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM