如何处理遗留代码中的方法名称重复

时间:2012-08-25 14:48:24

标签: c++ macros compiler-errors freebsd

我的遗留代码中有

#define max(x, y)   (x > y ? x : y)
#define min(x, y)   (x < y ? x : y)

该bean在应用程序中使用了allot,现在我尝试在freeBSD中编译它 我一直在说:

/usr/include/c++/4.2/bits/istream.tcc:123:35: error: macro "min" requires 2 arguments, but only 1 given
/usr/include/c++/4.2/bits/istream.tcc:124:45: error: macro "max" requires 2 arguments, but only 1 given
/usr/include/c++/4.2/bits/istream.tcc:143:33: error: macro "min" requires 2 arguments, but only 1 given
/usr/include/c++/4.2/bits/istream.tcc:144:43: error: macro "max" requires 2 arguments, but only 1 given
/usr/include/c++/4.2/bits/istream.tcc:438:48: error: macro "max" requires 2 arguments, but only 1 given
/usr/include/c++/4.2/bits/istream.tcc:441:53: error: macro "min" requires 2 arguments, but only 1 given
/usr/include/c++/4.2/bits/istream.tcc:449:47: error: macro "max" requires 2 arguments, but only 1 given
/usr/include/c++/4.2/bits/istream.tcc:489:48: error: macro "max" requires 2 arguments, but only 1 given
/usr/include/c++/4.2/bits/istream.tcc:493:53: error: macro "min" requires 2 arguments, but only 1 given
/usr/include/c++/4.2/bits/istream.tcc:501:47: error: macro "max" requires 2 arguments, but only 1 given
/usr/include/c++/4.2/bits/istream.tcc:507:53: error: macro "max" requires 2 arguments, but only 1 given
/usr/include/c++/4.2/bits/istream.tcc:806:43: error: macro "max" requires 2 arguments, but only 1 given

我猜它是代码中的方法名称(宏) 现在把名字改成了很多工作。
我怎样才能继续使用它,但避免编译器混淆?

1 个答案:

答案 0 :(得分:4)

首先定义这些宏的原因是什么?这是C ++,不需要任何宏,特别是那些已经作为标准赋予你功能的宏(当包括<windows.h>并且抱怨他们的愚蠢min和{{1 }。宏)。

话虽这么说,快速而肮脏的解决方案可能是用

替换你的宏定义
max

尽管如此,这仍然污染了全局命名空间,现在它们是正确的函数名,可以被任何局部变量或任何其他函数或方法隐藏,并且不会被一个愚蠢的文本替换预处理器替换到任何地方。

除此之外,考虑在这些宏(或#include <algorithm> using std::min; using std::max; s)之前包含任何系统包含文件。