Debug print trace macro

March 22, 2013 Coded in C

Far be it for me to encourage over-use of preprocessor macros, but the ability of the preprocessor to embed file, function and line information makes it useful for debug trace.  The use of the standard built-in NDEBUG macro allows the code to be automatically excluded on release builds.

Note that the lack of a comma between `"%s::%s(%d)"` and `format` is deliberate. It prints a formatted string with source location prepended. 

For many systems with critical timing it is often useful to also include a timestamp using a suitable system-wide clock source, but since that is system dependent I have omitted that option from the example.  Note that where timing is critical you should ensure that your stdout implementation is buffered and non-blocking.

Support for variadic macros may not be universal hacing been standardised in C99.

#if defined NDEBUG
    #define TRACE( format, ... )
    #define TRACE( format, ... )   printf( "%s::%s(%d) " format, __FILE__, __FUNCTION__,  __LINE__, __VA_ARGS__ )

// Example usage
void example()
    unsigned var = 0xdeadbeef ;
    TRACE( "var=0x%x", var ) ;

// Resultant output example:
//    example.c::example(5) var=0xdeadbeef


There are no comments yet!

Sorry, you need javascript enabled to post any comments.