可变参数 C/C++ 宏定义

#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;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值