Debug formatted output----based on C language 1. Using macro implementations
Example:
#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. Using functions to implement
Several key macros are used in the implementation process:
#include <stdarg.h>va_list argp;va_start(argp, fmt);va_end(argp);
To use the vsnprintf () function
vsnprintf()头文件:#include <stdarg.h>函数原型:int vsnprintf(char *str, size_t size, const char *format, va_list ap);函数说明:将可变参数格式化输出到一个字符数组
Example:
#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;}
Summary
Through the above two methods can be implemented with debug output containing location information debugging information.
Debug formatted output----based on C language