是否在stdlib.h中定义了max(a,b)? [英] Is max(a,b) defined in stdlib.h or not?

查看:114
本文介绍了是否在stdlib.h中定义了max(a,b)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用两台计算机,每台计算机都具有不同版本的Visual Studio.在Visual Studio 2008计算机上,我的代码得以编译.在视觉2010计算机上,我的代码无法编译,因为我使用的是max(a,b)宏,据我所知,该宏是在stdlib.h中定义的.我不能只定义max(a,b),因为它将在visual 2008计算机上重新定义.但是,如果我未定义max(a,b),则我的代码将无法在Visual 2010计算机上编译.

I'm using two computers, each with a different version of visual studio. On the visual studio 2008 computer my code compiles. On the visual 2010 computer my code doesn't compile because I'm using the macro max(a,b) which as far as I know is defined in stdlib.h. I cannot just define max(a,b) because it'll be a redefinition on the visual 2008 computer. But if I don't define max(a,b) my code doesn't compile on the visual 2010 computer.

有解决方案吗?

推荐答案

任何在其标准标头中定义名为max的宏的C库都超出了我们的想象.幸运的是,如果需要支持这样的平台,一个简单的解决方法是在包含系统头之后,在任何自己的头/代码之前,#undef max(及其定义的任何其他有问题的宏).

Any C library which defines a macro named max in its standard headers is broken beyond imagination. Fortunately, an easy workaround if you need to support such platforms is to #undef max (and any other problematic macros it defines) after including the system headers and before any of your own headers/code.

请注意,其他所有人都说要将您的定义包装在#ifndef max ... #endif中.这不是一个好主意.在系统标头中定义max表示该实现者不称职,并且某些版本的环境可能具有不正确宏(例如,那些不能正确地用括号保护参数的宏,但我什至看到一个max宏在我的生命中至少一次执行了错误的min而不是max宏!).只需使用#undef并确保安全.

Note that everyone else is saying to wrap your definition in #ifndef max ... #endif. This is not a good idea. Defining max in a system header is an indication that the implementor was incompetent, and it's possible that certain versions of the environment have incorrect macros (for example, ones which do not properly protect arguments with parentheses, but I've even seen a max macro that was incorrectly performing min instead of max at least once in my life!). Just use #undef and be safe.

关于为什么stdlib.h不能定义max的原因,C标准非常具体地说明了为应用程序保留的名称以及为标准功能和/或实现内部使用的名称.这有很好的理由.在系统标题中定义可能与应用程序中使用的变量/函数名称冲突的宏名称很危险.在最佳情况下,它会导致编译时错误,其原因显而易见,但在其他情况下,它会导致非常奇怪的行为,难以调试.在任何情况下,编写可移植代码都非常困难,因为您永远都不知道库将已经采用了什么名称.

As for why it's so broken for stdlib.h to define max, the C standard is very specific about what names are reserved for the application and what names are reserved for standard functions and/or internal use by the implementation. There are very good reasons for this. Defining macro names in system headers that could clash with variable/function names used in the application program is dangerous. In the best case it leads to compile-time errors with an obvious cause, but in other cases it can cause very strange behavior that's hard to debug. In any case it makes it very difficult to write portable code because you never know what names will already be taken by the library.

这篇关于是否在stdlib.h中定义了max(a,b)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆