#define macro for debug printing in C?

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

    For a portable (ISO C90) implementation, you could use double parentheses, like this;

    #include 
    #include 
    
    #ifndef NDEBUG
    #  define debug_print(msg) stderr_printf msg
    #else
    #  define debug_print(msg) (void)0
    #endif
    
    void
    stderr_printf(const char *fmt, ...)
    {
      va_list ap;
      va_start(ap, fmt);
      vfprintf(stderr, fmt, ap);
      va_end(ap);
    }
    
    int
    main(int argc, char *argv[])
    {
      debug_print(("argv[0] is %s, argc is %d\n", argv[0], argc));
      return 0;
    }
    

    or (hackish, wouldn't recommend it)

    #include 
    
    #define _ ,
    #ifndef NDEBUG
    #  define debug_print(msg) fprintf(stderr, msg)
    #else
    #  define debug_print(msg) (void)0
    #endif
    
    int
    main(int argc, char *argv[])
    {
      debug_print("argv[0] is %s, argc is %d"_ argv[0] _ argc);
      return 0;
    }
    

提交回复
热议问题