A simple MACRO to implement a debug printf

During normal coding stage, often I need to put some prints to reach a fast debug of my code. At the same time, I want to see how the code works without these prints.
Naturally I don't want to remove all prints and then add them again.
I have two solutions for this problem:
 
 
First solution:

I can add a #define as follows:
 

#define DEBUG

and then each time I want to print debug information I can use the "#ifdef #endif" construct. For example:
 
#ifdef DEBUG
           printf("debug info number 1\n");
#endif
.................
           // some stuff

#ifdef DEBUG
           printf("debug info number 2\n");
#endif
 
to remove the debug prints, I only need to remove "#define DEBUG" from my code.
 
Second solution:
I can add a #define as follows:
 
#define DEBUG

then I can define a new MACRO as follows:
 
#ifdef DEBUG
#define PRINTD printf
#else
#define PRINTD(format, args...) ((void)0)
#endif
 
and then each time I want to print debug information I can use the new PRINTD macro. For example:
 
           PRINTD ("debug info number 1\n");
.................
           // some stuff

           PRINTD ("debug info number 2\n");
 
to remove the debug prints, I only need to remove "#define DEBUG" from my code.
 
This second solution is my favourite one because the code is cleaner than the code in the first solution
Gg1

You may also like...

3 Responses

  1. Jac Goudsmit says:

    For those working with older C compilers that don't support variable macro arguments, you can do this:

    #ifdef DEBUG

      #define PRINTD(x) printf

    #else

      #define PRINTD(x) (void(0))

    #endif



    PRINTD(("Hello debugger\n"));

    PRINTD(("The number you dialed, %u, is not in service\n", 911));




  2. Jac Goudsmit says:

    oops that should be
    #define PRINTD(x) printf x

Leave a Reply

Your email address will not be published. Required fields are marked *