#include <stdio.h>
#include <stdarg.h>
// #define __FUNCTION__ NULL
/* 宏可变参数的几种定义和使用方法 */
#define DEBUG
#ifdef DEBUG
// debug 版本定义宏调试
// 方式一 C99 支持 __VA_ARGS__
#define LOG(format, ...) \
my_printf(format, __VA_ARGS__)
// 方式二 gcc默认支持
#define LOG_A(format, args...) \
my_printf(format, args)
/*
方式一 和 方式二 不能缺省可变参数
方式三 和 方式四 可以缺省
*/
// 方式三
#define LOG_B(format, ...) \
my_printf("func:%s,time:%u " format, __FUNCTION__, __LINE__, ##__VA_ARGS__)
// 方式四
#define LOG_C(format, args...) \
my_printf(format, ##args)
#else
// release 版本 定义空宏,不做任何事情
#endif
// C99 支持的可变参数宏
#define LOG_PRINT(...) \
printf(__VA_ARGS__)
// 对于 __FUNCTION__ 和 __LINE__ 的使用
int var_arg(const char *format, const char *funcName, int line, ...)
{
char buff[4096] = {0};
printf("format %s\n funcname %s fun\n line %d\n", format, funcName, line);
va_list args;
va_start(args, line);
vsnprintf(buff, sizeof(buff), format, args);
va_end(args);
printf("va_args: %s\n", buff);
}
void my_printf(const char *format, ...)
{
char buff[4096] = {0};
va_list args;
va_start(args, format);
vsnprintf(buff, sizeof(buff), format, args);
va_end(args);
printf("my_print: %s\n", buff);
}
int main()
{
// var_arg("1 %s 2 %d", __FUNCTION__, __LINE__, "hello", 5); // 对于 __FUNCTION__ 和 __LINE__ 的使用
// LOG("debug log %s","hello"); // 正确
// LOG("debug log"); // 编译错误 不能缺省可变参数
// LOG_A("debug log A %s", "hello");
// LOG_A("debug log A"); // 编译错误 同理
// LOG_B("debug log B %s", "hello");
// LOG_B("debug log B"); // 正确 可以缺省可变参数
// LOG_C("debug log C %s", "hello");
// LOG_C("debug log C"); // 正确 可以缺省可变参数
// LOG_PRINT("hello %d", 5); // 可变参数宏 __VA_ARGS__ 的特别使用
return 0;
}
因篇幅问题不能全部显示,请点此查看更多更全内容