Debug格式化输出----基于C语言

来源:互联网 发布:c语言英文怎么说 编辑:程序博客网 时间:2024/05/20 03:38

Debug格式化输出—-基于C语言

  • Debug格式化输出-基于C语言
      • 使用宏实现
      • 使用函数实现
      • 小结

1. 使用宏实现

举例:

#include <stdio.h>#define ECHO_COLOR_NONE         "\033[0;0m"#define ECHO_COLOR_GREEN        "\033[0;32m"#define debug(fmt, args...)     \          printf(ECHO_COLOR_GREEN"Debug: " fmt "(file: %s, func: %s, line: %d)\n"ECHO_COLOR_NONE, ##args, __FILE__, __func__, __LINE__);
// 测试程序int main(void){     int data = 10;     debug("This is a test, data = %d", data);     printf("OK\n");     return 0;}

2. 使用函数实现

在实现过程中要用到几个关键宏:

#include <stdarg.h>va_list argp;va_start(argp, fmt);va_end(argp);

要用到vsnprintf()函数

vsnprintf()头文件:#include <stdarg.h>函数原型:int vsnprintf(char *str, size_t size, const char *format, va_list ap);函数说明:将可变参数格式化输出到一个字符数组

举例:

#include <stdio.h>#include <stdarg.h>#define ECHO_COLOR_NONE         "\033[0;0m"#define ECHO_COLOR_GREEN        "\033[0;32m"#define debug_print(message, ...)   debug_msg(message, __FILE__, __func__, __LINE__, ##__VA_ARGS__)void debug_type(char *fmt, char *file, const char *func, int line, va_list argp){     char buffer[128] = { 0 };     vsnprintf(buffer, sizeof(buffer), fmt, argp);     printf(ECHO_COLOR_GREEN"Debug: %s(file: %s, func: %s, line: %d)\n"ECHO_COLOR_NONE, buffer, file, func, line);}void debug_msg(char *fmt, char *file, const char *func, int line, ...){     va_list arg_list;     va_start(arg_list, line);     debug_type(fmt, file, func, line, arg_list);     va_end(arg_list);}
// 测试程序int main(void){     int data = 10;     debug_print("This is a test, data = %d", data);     printf("OK\n");     return 0;}

小结

通过以上两种方法就可以实现用debug输出含有位置信息的调试信息。

原创粉丝点击