항상 C++로 코딩을 하면서 min()이나 max() 함수(최소값/최대값을 리턴하는 함수)를 쓸때 이상한 에러를 맞닥뜨리곤 한다.
나중에 안 사실이지만 이 것은 min()/max() 라는 이름으로 선언된 함수들끼리 서로 충돌을 일으키기 때문이다. 즉 include 한 header 파일 내에 동일한 이름으로 다른 함수들이 선언되어 있는 것이다.
몇가지 해결책을 이 블로그에서 찾았다. 해결책은 아래와 같다.
I always confronted something weird errors when I use min() or max() function in C++.
Actually, it because of conflicts between the functions with same name.
I found several solutions for this problems from this blog post.
And solutions suggested are following. (prioritized with best approach first):
이하 내용은 블로그에서 인용.
Following suggestions are cited from the blog.
- Convert your source code to use the Standard C++ std::min() and std::max() and ensure that you #include . Use
#include <algorithm> using namespace std; // use min() instead of std::min() // use max() instead of std::max()
- Define the NOMINMAX macro to instruct WinDef.h not to define the min/max macros. E.g. you can update your Visual C++ compiler options with /D NOMINMAX or you can insert #define NOMINMAX.
-
Redefine min/max in the specific problematic files. Especially this may be needed in you include gdiplus Windows headers files, because these uses the Windows min/max macros.
#include <algorithm> #ifndef max #define max(a,b) (((a) > (b)) ? (a) : (b)) #endif #ifndef min #define min(a,b) (((a) < (b)) ? (a) : (b)) #endif #include <gdiplus.h> #undef max #undef min using namespace std;
- Alternatively redefine min/max to use use the Visual C++ non-standard __min()/__max(). But min/max are still defined as macros and will likely lead to problems. Not a good solution.
#ifndef max #define max __max #endif #ifndef min #define min __min #endif
- Alternatively use Visual C++ compiler options /Dmin=__min / Dmax=__max. This will tell compiler and WinDef.h not to define min/max macros and use __min() and __max() functions instead as defined in (or ) so ensure this is included. But min/max are still defined as macros and will likely lead to problems. Not a good solution.
Thanks to Michael Suodenjoki !