C/C++ 可变参数宏方法总结

C/C++ 可变参数宏

本文链解:https://blog.csdn.net/Sharpneo/article/details/131219346

目前大致有以下几种方式实现可变参数宏,总结如下:

1. 调用宏时多加一对括号实现

#include <stdio.h>
#define DEBUG(massage) {printf("[ERROR]:");printf massage;}

int main(){
    DEBUG(("msg %d\n", 1));
    DEBUG(("msg\n"));
    return 0;
}
/* Output:
[ERROR]:msg 1
[ERROR]:msg
*/

这种方式的缺点是使用该宏时必须多加一对括号,好处是兼容C99之前的标准。

C99标准之后引入了之后的三种更优雅的方式来实现可变参数

2. 编译器预定宏__VA_ARGS__

#include <stdio.h>
#define DEBUG(massage,...) {printf("[ERROR]:");printf(massage,__VA_ARGS__);}

int main(){
    DEBUG("msg %d\n", 1);
    // DEBUG("msg\n");编译报错
    return 0;
}

这种写法宏函数可以像普通可变参数函数一样使用...来标记可变参数,并通过__VA_ARGS__宏来传递参数,缺点是当宏没有可变参数时,参数列表末尾会多出一个逗号,导致编译错误。

3. ##__VA_ARGS__

#include <stdio.h>
#define DEBUG(massage,...) {printf("[ERROR]:");printf(massage,##__VA_ARGS__);}

int main(){
    DEBUG("msg %d\n", 1);
    DEBUG("msg\n");
    return 0;
}

这种方法是为解决2.所提出的问题,当没有可变参数时,##__VA_ARGS__会自动去除前面的逗号,保证了编译不会报错。

4. 自定义参数名称

#include <stdio.h>
#define DEBUG(massage,arg...) {printf("[ERROR]:");printf(massage,arg);}

int main(){
    DEBUG("msg %d\n", 1);
    // DEBUG("msg\n");编译报错
    return 0;
}

这种写法只需要在...前面加入自己的宏参数名,就可以将__VA_ARGS__替换为自己想要的名称,如上述例子中使用的arg。因为没有在arg前加入##所以依旧存在逗号引起的编译问题。

5. 终极形态

#include <stdio.h>
#define DEBUG(massage,arg...) {printf("[ERROR]:");printf(massage,##arg);}

int main(){
    DEBUG("msg %d\n", 1);
    DEBUG("msg\n");
    return 0;
}

在gcc和clang编译器中的测试结果:
在这里插入图片描述

应用场景

可以用在日志信息输出时,将日志信息定向到不同的输出目标,除使用printf输出到设备外,还可以自定义输出到文件。

下面展示了一个实例:
用户可以在配置文件log_conf.h中定义不同级别日志信息的输出方式,当用户配置文件log_conf.h中未定义的时候,默认配置文件log_conf_default.h可以保证代码正常编译运行。

// log_conf.h
#define ERROR(massage,arg...) {printf("[ERROR]:");printf(massage,##arg);}
#define WARN(massage,arg...) {printf("[WARN]:");printf(massage,##arg);}
#define INFO(massage,arg...) {printf("[INFO]:");printf(massage,##arg);}
#define DEBUG(massage,arg...) {printf("[DEBUG]:");printf(massage,##arg);}
// log_conf_default.h
#include "log_conf.h"

#ifndef ERROR
#define ERROR(massage,arg...)
#endif

#ifndef WARN
#define WARN(massage,arg...)
#endif

#ifndef INFO
#define INFO(massage,arg...)
#endif

#ifndef DEBUG
#define DEBUG(massage,arg...)
#endif
// main.c
#include "log_conf_default.h"
int main(){
    DEBUG("msg %d\n", 1);
    ERROR("msg\n");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值