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?
In Visual C++, if you
#define NOMINMAX
before including the standard headers, you will not get a macromax
ormin
.So answering your main question:
No it isn't, it's defined in windef.h around line 187:
you can use condition compiling:
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. Definingmax
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 amax
macro that was incorrectly performingmin
instead ofmax
at least once in my life!). Just use#undef
and be safe.As for why it's so broken for
stdlib.h
to definemax
, 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.Protect it with an
#ifndef
.Keep in mind that the version above is not as safe as an inline function, e.g.
max(a++,b--)
will cause unxpected results.