在C中调试打印宏?

w7t8yxp5  于 2023-03-11  发布在  其他
关注(0)|答案(8)|浏览(137)

在C语言中,定义一个类似printf的宏的正确方法是什么,这个宏只有在定义了DEBUG符号时才打印?

#ifdef DEBUG
#define DEBUG_PRINT(???) ???
#else
#define DEBUG_PRINT(???) ???
#endif

where???是指我不确定要填写什么的地方

gojuced7

gojuced71#

我见过很多这样的成语:

#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。

7uzetpgm

7uzetpgm2#

#ifdef DEBUG
#define DEBUG_PRINT(...) do{ fprintf( stderr, __VA_ARGS__ ); } while( false )
#else
#define DEBUG_PRINT(...) do{ } while ( false )
#endif
jmo0nnb3

jmo0nnb33#

比如:

#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
toe95027

toe950274#

谢谢你的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
6fe3ivhb

6fe3ivhb5#

使用不同的DEBUG_PRINT签名,它们不必相同,例如:

#ifdef DEBUG
#define DEBUG_PRINT printf
#else
#define DEBUG_PRINT(...)
#endif

这样在调试模式下,DEBUG_PRINT调用将被printf代替。2在释放时,它将忽略之前使用的所有参数。
希望有帮助。

wnrlj8wa

wnrlj8wa6#

您可以简单地用途:

#ifdef DEBUG
    #define DEBUG_PRINT printf
#else
    #define DEBUG_PRINT
#endif
llycmphe

llycmphe7#

我最喜欢这种方式,因为它不会向您的发布版本添加任何asm指令。

#define DEBUG
#ifdef DEBUG
#define  debug_printf(fmt, ...)  printf(fmt, __VA_ARGS__);
#else
#define debug_printf(fmt, ...)    /* Do nothing */
#endif
uemypmqf

uemypmqf8#

我在the implementation in the main answer中发现了一些小错误。因此,下面是我的方法:

#ifdef DEBUG
    #define DEBUG_PRINTF(...) printf("DEBUG: " __VA_ARGS__)
#else
    #define DEBUG_PRINTF(...) do {} while (0)
#endif

示例用法:

DEBUG_PRINTF("hello\n");

然后,如果我在C编译选项中使用-DDEBUG define on进行编译和运行,如下所示:

# Build
gcc -Wall -Wextra -Werror -std=c11 -DDEBUG -o build/my_program \
my_program_tests.c my_program.c

# Run
build/my_program

然后我看到这个输出:

DEBUG: hello

但是如果我在编译器C选项中没有定义-DDEBUG,那么我看不到任何调试打印。

其他参考文献

1.使其也与C++兼容的修复方法:https://stackoverflow.com/a/72777133/4561887:在__VA_ARGS__前添加一个空格。使用"DEBUG: " __VA_ARGS__代替"DEBUG: "__VA_ARGS__

相关问题