Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is std::min failing when windows.h is included?

The windows.h header file (or more correctly, windef.h that it includes in turn) has macros for min and max which are interfering.

You should #define NOMINMAX before including it.


No need to define anything, just bypass the macro using this syntax:

(std::min)(a, b); // added parentheses around function name
(std::max)(a, b);

I still have trouble occasionally with the windows headers and project wide define of NOMINMAX doesn't always seem to work. As an alternative to using parentheses, I sometimes make the type explicit like so:

auto k = std::min<int>(3, 4);

This also stops the preprocessor from matching to min and is arguably more readable than the parentheses workaround.


As others mentioned, the errors are due to min/max macros that are defined in windows header(s). There are three ways of disabling them.

1) #define NOMINMAX before including header, this is generally a bad technique of defining macros in order to affect the following headers;

2) define NOMINMAX in compiler command line/IDE. The bad part about this decision is that if you want to ship your sources, you need to warn the users to do the same;

3) simply undefine the macros in your code before they are used

#undef min
#undef max

This is probably the most portable and flexible solution.