#define macro for debug printing in C?

后端 未结 12 1828
夕颜
夕颜 2020-11-21 23:59

Trying to create a macro which can be used for print debug messages when DEBUG is defined, like the following pseudo code:

#define DEBUG 1
#define debug_prin         


        
12条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 00:35

    I use something like this:

    #ifdef DEBUG
     #define D if(1) 
    #else
     #define D if(0) 
    #endif
    

    Than I just use D as a prefix:

    D printf("x=%0.3f\n",x);
    

    Compiler sees the debug code, there is no comma problem and it works everywhere. Also it works when printf is not enough, say when you must dump an array or calculate some diagnosing value that is redundant to the program itself.

    EDIT: Ok, it might generate a problem when there is else somewhere near that can be intercepted by this injected if. This is a version that goes over it:

    #ifdef DEBUG
     #define D 
    #else
     #define D for(;0;)
    #endif
    

提交回复
热议问题