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
Posted by at June 14, 2011
Filed in category: micro controllers, The Prince: C, Tower of Babel, UNIX TLC, xAppSoftware News, and tagged with: , ,

3 Responses to A simple MACRO to implement a debug printf

  1. Pingback: Una semplice macro che implementa una printf di debug | Microprogrammo

  2. 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));




  3. 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 *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

%d bloggers like this: