C语言宏冲突##

问题描述

现存在头文件mylog.h和源文件myprog.cpp,内容如下:
mylog.h:

#ifndef MY_LOG_H_
#define MY_LOG_H_

#define log(level,fmt,...) \
        MyLog(level, fmt, ##__VA_ARGS__);

#endif

myprog.cpp:

#include "mylog.h"
#include "json/json.h"

int main()
{
    return 0;
}

在预编译时会出现如下错误:

# g++  -g -Wall -Wshadow -DJSON_IS_AMALGAMATION -I your include path -I./ -E myprog.cpp -o myprog.i
# In file included from /usr/include/math.h:65,
                 from /usr/include/c++/3.2.2/cmath:51,
                 from /usr/include/c++/3.2.2/bits/locale_facets.tcc:41,
                 from /usr/include/c++/3.2.2/locale:46,
                 from /usr/include/c++/3.2.2/bits/ostream.tcc:37,
                 from /usr/include/c++/3.2.2/ostream:275,
                 from /usr/include/c++/3.2.2/iostream:45,
                 from /your include path/json/json.h:1448,
                 from myprog.cpp:2:
/usr/include/bits/mathcalls.h:110:35: macro "log" requires 3 arguments, but only 1 given

根因分析

打开/usr/include/bits/mathcalls.h文件,在110行我们可以看到如下内容:

/* Natural logarithm of X.  */
 __MATHCALL (log,, (_Mdouble_ __x));

该行代码定义了对数函数的宏,该宏名称为log,参数数量为1;而在我们定义的头文件mylog.h中,同样定义了log宏,参数数量为3;所以,两个文件的log宏定义产生了冲突,才会发生以上问题。

解决方法

在”myprog.cpp”中,包含”json/json.h”头文件前,先释放log宏的定义,包含”json/json.h”头文件后,再覆盖log宏的定义。代码如下:

#include "mylog.h"

#ifdef log
#undef log
#include "json/json.h"
#define log(level,fmt,...) \
        MyLog(level, fmt, ##__VA_ARGS__);

int main()
{
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值