Debug printf()

While debugging, we often add fprintf() statements to help us get an idea of what exactly is going on. Once having done that, we need to somehow clean up the extra output.

The mechanism I use is to put the debug print statements as an argument to a macro, DBG(), as follows:

	DBG( fprintf(stderr, "int_stack: pushed %d onto %p\n", val, stack));

This macro's defineition is controlled by the value of another constant. For a file foo.c, by convention, the name of the control constant is DEBUG_FOO. Thus, for int_stack.c, DBG() would be defined as:

	  #define DBG(_x)	((void)(_x))
	  #define DBG(_x)	((void)0)

Thus, by setting the value of DEBUG_INT_STACK to 0/non-0, we can turn debug output off/on. The control value is, in turn, defined as:

	  #define DEBUG_INT_STACK 0

This allows us to turn debugging on through the compiler, simply by adding the -DDEBUG_INT_STACK=1 flag (or equivalent) to the arguments for compiling int_stack.c.

For small programs, this is enough. However, for large programs, where we are seeing lots of debug output from multiple files, it is easy to lose track of where the debug message came from. To keep track of the sources of messages we actually define DBG() as:

	#define DBG(_x) \
		( fprintf(stderr, "%s %d: ", __FILE__, __LINE__), \
	#define DBGN(_x) \
		( (void)(_x))

This way DBG() automatically puts the source file/line number before each message. If we don't want the source to be prepended, we use DBGN().

Next Prev Main Top Feedback