Is max(a,b) defined in stdlib.h or not?

2020-05-25 18:18发布

问题:

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.

Any solution?

回答1:

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.

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.

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.



回答2:

So answering your main question:

Is max(a,b) defined in stdlib.h or not?

No it isn't, it's defined in windef.h around line 187:

#ifndef NOMINMAX

#ifndef max
#define max(a,b)            (((a) > (b)) ? (a) : (b))
#endif

#ifndef min
#define min(a,b)            (((a) < (b)) ? (a) : (b))
#endif

#endif  /* NOMINMAX */


回答3:

Protect it with an #ifndef.

#ifndef max
    #define max(a,b) ((a) > (b) ? (a) : (b))
#endif

Keep in mind that the version above is not as safe as an inline function, e.g. max(a++,b--) will cause unxpected results.



回答4:

you can use condition compiling:

#ifndef max
  #define max(a,b) ...
#endif


回答5:

In Visual C++, if you #define NOMINMAX before including the standard headers, you will not get a macro max or min.