Aussie AI

Debug Tracing Messages

  • Book Excerpt from "Generative AI in C++"
  • by David Spuler, Ph.D.

Debug Tracing Messages

A common debugging method is adding debug trace output statements to a program to print out important information at various points in the program. Judicious use of these statements can be highly effective in localizing the cause of an error, but this method can also lead to huge volumes of not particularly useful information. One desirable feature of this method is that the output statements can be selectively enabled at either compile-time or run-time.

Debug tracing messages are informational messages that you only enable during debugging. These are useful to software developers to track where the program is executing, and what data it is processing. The simplest version of this idea looks like:

    #if DEBUG
    std::cerr << "DEBUG: I am here!" << std::endl;
    #endif

A better solution is to code some BYO debug tracing macros. Here's a C-like version:

   #define ydebug(str)  ( fprintf(stderr, "%s\n", (str)) )
   ... 
   ydebug("DEBUG: I am here!");

And here's the C++ style version:

   #define ydebug(str)  ( std::cerr << str << std::endl )
   ... 
   ydebug("DEBUG: I am here!");

In order to only show these when debug mode is enabled in the code, our header file looks like this:

   #if DEBUG
       #define ydebug(str)  ( std::cerr << str << std::endl )
   #else
       #define ydebug(str) // nothing
  #endif

Missing Semicolon Bug: Professional programmers prefer to use “0” rather than emptiness to remove the debug code when removing it from the production version. It is also good to typecast it to “void” type so it cannot accidentally be used as the number “0” in expressions. Hence, we get this improved version:

    #define ydebug(str) ((void)0)  // better!

It's not just a stylistic preference. The reason is that the “nothing” version can introduce an insidious bug if you forget a semicolon after the debug trace call in an if statement:

   if (something) ydebug("Hello world") // Missing semicolon
   x++;

If the “nothing” macro expansion is used, then the missing semicolon leads to this code:

   if (something) // nothing
   x++;

Can you see why it's a bug? Instead, if the expansion is “((void)0)” then this missing semicolon typo will get a compilation error.

 

Next:

Up: Table of Contents

Buy: Generative AI in C++: Coding Transformers and LLMs

Generative AI in C++ The new AI programming book by Aussie AI co-founders:
  • AI coding in C++
  • Transformer engine speedups
  • LLM models
  • Phone and desktop AI
  • Code examples
  • Research citations

Get your copy from Amazon: Generative AI in C++