C调试打印宏
在C中,定义类似printf的宏的正确方法是什么,只有在定义了DEBUG符号时才会打印?
#ifdef DEBUG #define DEBUG_PRINT(???) ??? #else #define DEBUG_PRINT(???) ??? #endif
哪里??? 是我不知道该填写什么的地方
我已经看到了这个成语很多:
#ifdef DEBUG # define DEBUG_PRINT(x) printf x #else # define DEBUG_PRINT(x) do {} while (0) #endif
使用它像:
DEBUG_PRINT(("var1: %d; var2: %d; str: %s\n", var1, var2, str));
额外的括号是必要的,因为一些较旧的C编译器不支持宏中的var-args。
#ifdef DEBUG #define DEBUG_PRINT(...) do{ fprintf( stderr, __VA_ARGS__ ); } while( false ) #else #define DEBUG_PRINT(...) do{ } while ( false ) #endif
就像是:
#ifdef DEBUG #define DEBUG_PRINT(fmt, args...) fprintf(stderr, fmt, ## args) #else #define DEBUG_PRINT(fmt, args...) /* Don't do anything in release builds */ #endif
谢谢mipadi,我也用文件信息改进了你的DEBUG_PRINT。
#define DEBUG 3 #if defined(DEBUG) && DEBUG > 0 #define DEBUG_PRINT(fmt, args...) fprintf(stderr, "DEBUG: %s:%d:%s(): " fmt, \ __FILE__, __LINE__, __func__, ##args) #else #define DEBUG_PRINT(fmt, args...) /* Don't do anything in release builds */ #endif
测试最新的铿锵声,例如
int main(int argc, char **args) { DEBUG_PRINT("Debugging is enabled.\n"); DEBUG_PRINT("Debug level: %d", (int) DEBUG); }
输出:
DEBUG: debug.c:13:main(): Debugging is enabled. DEBUG: debug.c:14:main(): Debug level: 3
你可以简单地使用:
#ifdef DEBUG #define DEBUG_PRINT printf #else #define DEBUG_PRINT #endif
使用DEBUG_PRINT的不同签名,它们不必相同,例如:
#ifdef DEBUG #define DEBUG_PRINT printf #else #define DEBUG_PRINT(...) #endif
这样在调试模式下,DEBUG_PRINT调用将替换为printf。 在发布时,它将忽略之前使用的所有参数。
希望能帮助到你。