我正在使用Visual C ++ 2008进行开发。在项目中,我需要包含两个标题(例如一个是aaa.h
,另一个是bbb.h
),由第三方提供。
不幸的是,标题aaa.h中有一个名为“Log()”的宏,以及标题bbb.h中名为“Log()”的函数。
众所周知,如果标头aaa.h
在源文件中位于bbb.h
之前,则该函数将在预编译过程中展开并导致构建错误。现在,我必须在aaa.h
之后将标题bbb.h
放在每个源文件中。但是有许多源文件需要包含这两个文件。如果我修改每个文件,则需要付出太多努力。
实际上,我只需要在代码中使用宏。该功能对我的项目毫无用处。但是标题属于第三方,我无法修改它。
你有更好的方法吗?
答案 0 :(得分:0)
使用#undef Log,您也可以使用不同的名称从aaa.h复制宏定义,这样您就可以使用它而不会与bbb.h中的函数冲突。
答案 1 :(得分:0)
我从来没有遇到过你所描述的情况,所以可能有更好的解决方案,但是每当你想使用这个功能时,你可能只需要#undef
宏。
#include "bbb.h"
#include "aaa.h"
// ...
void foo()
{
// I want to use the macro here
Log();
}
void bar()
{
// I want to use the regular function here
#undef Log
Log();
}
答案 2 :(得分:0)
嗯,这就是为什么我们避免使用宏,因为它们没有作用域,这意味着你的选择非常有限。
你可以:
#undef
宏。......就是这样。
答案 3 :(得分:0)
作为解决方法,您可以创建
// bbb_fixed.h
#if defined(Log)
# if defined(__GNUC__) || defined(_MSC_VER) // Maybe other compilers, maybe check version too
# pragma push_macro("Log")
# undef Log
# include "bbb.h"
# pragma pop_macro("Log")
# else
# undef Log
# include "bbb.h"
// Now restore manually Log macro:
# define Log // code from #include "aaa.h"
//# undef AAA_H // aaa.h include guards
//# #include "aaa.h"
#else // Lod undefined
# include "bbb.h"
#endif
并添加bbb_fixed.h
代替bbb.h
但更好的方法是将标题aaa.h
修复为不使用此类宏。
答案 4 :(得分:0)
如果bbb.h中的其他内容不需要Log()函数,则从bbb.h中删除Log()函数
如果文件需要bbb.h,则不需要Log宏: 在bbb.h中添加一个保护字;检查aaa.h中的保护词;如果存在保护字,则undef Log宏。 (如果需要两个标题,请在aaa.h之前包含bbb.h。)
示例:
bbb.h
#ifndef GUARD_BBB_H
#define GUARD_BBB_H
#endif
....
aaa.h
#ifndef GUARD_BBB_H
#define Log() // Log Marco
#endif
如果两者都需要,您可能需要重命名Log macro。
编辑: 如果可以执行函数重载,则可以将Log宏修改为Log函数。