tags:

views:

197

answers:

2

Hi,

I am using the following macro for printing debug information that I found on the web. It works great. However, I would like to turn-off debug printing for function A when debugging function B, which calls function A. I tried #define NDEBUG function A #undef NDEBUG but haven't managed to suppress printing in function A.

Any help will be greatly appreciated. Any suggestions for alternative ways of accomplishing the task is also welcome.

Thanks ~RT

#ifdef NDEBUG
/*
  If not debugging, DEBUGPRINT NOTHING.
*/
#define DEBUGPRINT2(...) 
#define DEBUGPRINT(_fmt,G ...) 
#else
/*
  Debugging enabled:
*/
#define WHERESTR  "[file %s, line %d]: "
#define WHEREARG  __FILE__, __LINE__
#define DEBUGPRINT2(...)       fprintf(stderr, __VA_ARGS__)
#define DEBUGPRINT(_fmt, ...)  DEBUGPRINT2(WHERESTR _fmt, WHEREARG, __VA_ARGS__)
#endif /* NDEBUG */
A: 

NDEBUG is useful at the time assert.h is included, so #define NDEBUG/#undef NDEBUG later will not do anything.

You can do something like this though:

#if defined(NDEBUG) || !defined(MY_DEBUG)
/*
  If not debugging, DEBUGPRINT NOTHING.
*/
#define DEBUGPRINT2(...) 
#define DEBUGPRINT(_fmt,G ...) 
#else
/*
  Debugging enabled:
*/
#define WHERESTR  "[file %s, line %d]: "
#define WHEREARG  __FILE__, __LINE__
#define DEBUGPRINT2(...)       fprintf(stderr, __VA_ARGS__)
#define DEBUGPRINT(_fmt, ...)  DEBUGPRINT2(WHERESTR _fmt, WHEREARG, __VA_ARGS__)
#endif /* NDEBUG */

Then, in function A():

...
#undef MY_DEBUG
result = B();
#define MY_DEBUG
...

This will debug B() when it's called from anywhere except from A(). To get debugging, you will need MY_DEBUG to be defined and NDEBUG to be undefined.

Edit: You will need to define MY_DEBUG when you want to compile with debugging, but hopefully you're using make or some other build tool, so this should be easy.

Alok
Hi Alok, Thankshis for the response. I was not able to get this to work. It seems that the only way I can enable/disable debugging macros is to have NDEBUG//MY_DEBUG defined/undefined BEFORE the macro definition. Use of #define / #undef after the macro itself has been defined seems to have no effect as a switch. ~rt
Please see my edit. You want to define MY_DEBUG and not define NDEBUG when you want debugging. If you define NDEBUG or not define MY_DEBUG, there will be no debugging. All these "defining" has to happen when compiling, for example: `gcc -DMY_DEBUG file.c`.
Alok
+1  A: 

maybe you should wrap the trace into a module so that you can turn on/off the tracing dynamically in run-time and in that way you can specifically turn it off for a function call. In release mode you could replace all tracing with empty statements although in my experience I find it good to keep tracing in release mode as well - just in case.

Anders K.