问题描述
现存在头文件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;
}