Aussie AI

Multi-Statement Debug Trace Macro

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

Multi-Statement Debug Trace Macro

An alternative method of using debugging statements is to use a special macro that allows any arbitrary statements. For example, debugging output statements can be written as:

    YDBG( printf("DEBUG: Entered function print_list\n"); )

Or using C++ iostream output style:

    YDBG( std::cerr << "DEBUG: Entered function print_list\n"; )

This allows use of multiple statements of debugging, with self-testing code coded as:

    YDBG( count++; )
    YDBG( if (count != count_elements(table)) { )
    YDBG(     aussie_internal_error("ERROR: Element count wrong"); )
    YDBG( } )

But it's actually easier to add multiple lines of code or a whole block in many cases. An alternative use of YDBG with multiple statements is valid, provided that the enclosed statements do not include any comma tokens (unless they are nested inside matching brackets). The presence of a comma would separate the tokens into two or more macro arguments for the preprocessor, and the YDBG macro above requires only one parameter:

    YDBG(
        count++; 
        if (count != count_elements(table)) { // self-test
            aussie_internal_error("ERROR: Element count wrong"); // error
        }
    )

The multi-statement YDBG macro is declared in a header file as:

    #if YDEBUG
    #define YDBG(token_list) token_list  // Risky
    #else
    #define YDBG(token_list) // nothing
    #endif

The above version of YDBG is actually non-optimal for the macro error reasons already examined. A safer idea is to add surrounding braces and the “do-while(0)” trick to the YDBG macro:

    #if YDEBUG
    #define YDBG(token_list) do { token_list } while(0)   // Safer
    #else
    #define YDBG(token_list)   ((void)0)
    #endif

Note that this now requires a semicolon after every expansion of the YDBG macro, whereas the earlier definition did not:

   YDBG( std::cerr << "Value of i is " << i << "\n"; );

Whenever debugging is enabled, the statements inside the YDBG argument are activated, but when debugging is disabled they disappear completely. Thus, this method offers a very simple method of removing debugging code from the production version of a program, if you like that kind of thing.

This YDBG macro may be considered poor style since it does not mimic any usual syntax. However, it is a neat and general method of introducing debugging statements, and is not limited to output statements.

 

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++