#define macro for debug printing in C?

后端 未结 12 1815
夕颜
夕颜 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:29

    My favourite of the below is var_dump, which when called as:

    var_dump("%d", count);

    produces output like:

    patch.c:150:main(): count = 0

    Credit to @"Jonathan Leffler". All are C89-happy:

    Code

    #define DEBUG 1
    #include 
    #include 
    void debug_vprintf(const char *fmt, ...)
    {
        va_list args;
        va_start(args, fmt);
        vfprintf(stderr, fmt, args);
        va_end(args);
    }
    
    /* Call as: (DOUBLE PARENTHESES ARE MANDATORY) */
    /* var_debug(("outfd = %d, somefailed = %d\n", outfd, somefailed)); */
    #define var_debug(x) do { if (DEBUG) { debug_vprintf ("%s:%d:%s(): ", \
        __FILE__,  __LINE__, __func__); debug_vprintf x; }} while (0)
    
    /* var_dump("%s" variable_name); */
    #define var_dump(fmt, var) do { if (DEBUG) { debug_vprintf ("%s:%d:%s(): ", \
        __FILE__,  __LINE__, __func__); debug_vprintf ("%s = " fmt, #var, var); }} while (0)
    
    #define DEBUG_HERE do { if (DEBUG) { debug_vprintf ("%s:%d:%s(): HERE\n", \
        __FILE__,  __LINE__, __func__); }} while (0)
    

提交回复
热议问题