One will always run into the problem that one needs more detailed output from a section at some time, and less verbose output at another time. Or the whole output should be more verbose, or you want to investigate a segfault.
There are some logging libraries (log4c for example). I however use the following approach:
debug.h:
#ifdef DEBUG
#define IFDEBUG if(1)
#else
#define IFDEBUG if(0)
#endif
#ifdef SEGV
#define IFSEGV if(1)
#else
#define IFSEGV if(0)
#endif
#define debug(str) IFDEBUG { printf("\tDEBUG[%s]: %s\n", AT, str); fflush(NULL); }
#define dump_i(str, var) IFDEBUG { printf("\tDEBUG[%s]: %s: %i\n", AT, str, var); fflush(NULL); }
#define dump_p(str, var) IFDEBUG { printf("\tDEBUG[%s]: %s: %p\n", AT, str, var); fflush(NULL); }
in your code:
debug("we are now doing foo ");
IFSEGV
dump_p("m\n", (void*)m);
IFDEBUG
printf("\t\tn_par=%d; status=%d\n", get_n_par(m), status);
Example output:
DEBUG[tests/tests.c:196]: add starting points, ...
This allows you to recompile your code with -DDEBUG -DSEGV and enable/disable verbosity levels without constant code changes.
#1 by JohannesBuchner on August 1st, 2010
REPLY:
Thanks, I never got around to look at variable arguments in the preprocessor
#2 by panzi on April 18th, 2009
I prefer something like this (requires C99):
debug.h:
main.c:
#include "debug.h" int main() { debugf("foo %s bar %d baz %f", "...", 42, 3.1415); return 0; }stderr should be unbuffered anyway, so I don’t need a fflush(stderr).