Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the reason to use DEBUG macro in C++?

I'm working on C++ program built by other people, and saw a lot of uses of DEBUG like this

#ifdef DEBUG
    cout << "Value is "<< value << endl;
#endif

I myself am still in the learning process to become an affluent C++ programmer, and I majorly use Visual Studio and breakpoints to debug. So I'm wondering, if I'm able to step through the code to debug values, is there any other reason to use these kind of macros?

Tried to google but didn't find much useful page.

Thanks.

like image 415
Derek Avatar asked May 31 '12 21:05

Derek


2 Answers

Sometimes you don't want to step through the whole code, but just inspect the output in the terminal.

If the code is compiled with DEBUG defined, probably in a debug build, you see the output. For a release build, you don't. If you go to project settings -> Configuration Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions, you'll see that DEBUG is defined for the debug build, but it's not for release. (I actually have _DEBUG)

Imagine you have a huge function, and what you're interested in is at the 1000th line (it's old code, can't change it). Would you rather step through all of that messy legacy code or have helpful debug statements at key points? Would you rather the console tell you where something went wrong, or set breakpoints at each of the 237 return statements at fail locations?

like image 187
Luchian Grigore Avatar answered Oct 09 '22 23:10

Luchian Grigore


While you're debugging, it is a common practice to dump some intermediate values on the screen. The visual debugger is not always helping, because you waste a lot of time manipulating with mouse.

The need for "text-mode debugging" and logging also frequently comes from the embedded systems experience, where you don't have much visual aid and all you can do is to dump a byte or two to serial port or something like that. When you get used to quickly finding critical debug points, you just insert some printing code there whose value checks the program correctness.

The "DEBUG" macro is defined by MSVC++ compiler while your project is compiled in Debug mode. When you're making the Release version, all the code which is actually useless for the end-users gets "stripped away" by the preprocessor.

Typical snippet

#ifdef DEBUG
Some code
#endif

is removed by the preprocessor if the DEBUG is not defined.

like image 34
Viktor Latypov Avatar answered Oct 10 '22 00:10

Viktor Latypov