#define macro for debug printing in C?

后端 未结 12 1647
夕颜
夕颜 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条回答
  •  -上瘾入骨i
    2020-11-22 00:17

    So, when using gcc, I like:

    #define DBGI(expr) ({int g2rE3=expr; fprintf(stderr, "%s:%d:%s(): ""%s->%i\n", __FILE__,  __LINE__, __func__, #expr, g2rE3); g2rE3;})
    

    Because it can be inserted into code.

    Suppose you're trying to debug

    printf("%i\n", (1*2*3*4*5*6));
    
    720
    

    Then you can change it to:

    printf("%i\n", DBGI(1*2*3*4*5*6));
    
    hello.c:86:main(): 1*2*3*4*5*6->720
    720
    

    And you can get an analysis of what expression was evaluated to what.

    It's protected against the double-evaluation problem, but the absence of gensyms does leave it open to name-collisions.

    However it does nest:

    DBGI(printf("%i\n", DBGI(1*2*3*4*5*6)));
    
    hello.c:86:main(): 1*2*3*4*5*6->720
    720
    hello.c:86:main(): printf("%i\n", DBGI(1*2*3*4*5*6))->4
    

    So I think that as long as you avoid using g2rE3 as a variable name, you'll be OK.

    Certainly I've found it (and allied versions for strings, and versions for debug levels etc) invaluable.

提交回复
热议问题