code

windows.h가 포함되어 있는데 std :: min이 실패하는 이유는 무엇입니까?

codestyles 2020. 8. 21. 07:46
반응형

windows.h가 포함되어 있는데 std :: min이 실패하는 이유는 무엇입니까?


#include <algorithm>
#include <Windows.h>

int main()
{
    int k = std::min(3, 4);
    return 0;
}

Windows.h를 포함하면 Windows는 무엇을합니까? std::minVisual Studio 2005에서 사용할 수 없습니다 . 오류 메시지는 다음과 같습니다.

error C2589: '(' : illegal token on right side of '::'
error C2059: syntax error : '::'

windows.h헤더 파일 (또는 더 정확하게, windef.h이 차례로 포함)을위한 매크로가 min하고 max있는 간섭있다.

#define NOMINMAX포함하기 전에 해야 합니다.


아무것도 정의 할 필요가 없습니다. 다음 구문을 사용하여 매크로를 우회하면됩니다.

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

다른 사람들이 언급했듯이 오류는 Windows 헤더에 정의 된 최소 / 최대 매크로로 인해 발생합니다. 비활성화하는 방법에는 세 가지가 있습니다.

1) #define NOMINMAX헤더를 포함하기 전에 이것은 일반적으로 다음 헤더에 영향을 미치기 위해 매크로를 정의하는 잘못된 기술입니다.

2) NOMINMAX컴파일러 명령 줄 / IDE에서 정의 합니다. 이 결정의 나쁜 점은 소스를 제공하려는 경우 사용자에게 동일한 작업을 수행하도록 경고해야한다는 것입니다.

3) 매크로를 사용하기 전에 코드에서 매크로를 정의 해제하십시오.

#undef min
#undef max

이것은 아마도 가장 휴대 가능하고 유연한 솔루션 일 것입니다.


나는 여전히 Windows 헤더에 문제가 있으며 NOMINMAX의 프로젝트 전체 정의가 항상 작동하지 않는 것 같습니다. 괄호를 사용하는 대신 다음과 같이 유형을 명시 적으로 만드는 경우가 있습니다.

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

이것은 또한 전처리 기가 일치하는 것을 중지 min하고 괄호 해결 방법보다 더 읽기 쉽습니다.


다음과 같이 시도하십시오.

#define NOMINMAX
#include <windows.h>

기본적으로 windows.h는 minmax매크로를 정의 합니다. 그것들이 확장되면 std::min(예를 들어) 사용하려는 코드는 다음과 같이 보일 것입니다.

int k = std::(x) < (y) ? (x) : (y);

오류 메시지는 std::(x)허용되지 않음을 알려줍니다 .


내 경우, 프로젝트는 포함하지 않았다 windows.h또는 windef.h명시 적으로. Boost를 사용하고있었습니다. 그래서 프로젝트로 이동 하여 (VS 2013, VS 2015)에 Properties -> C/C++ -> Preprocessor추가 하여 문제를 해결했습니다 .NOMINMAXPreprocessor Definitions


#define NOMINMAX

max와 min의 매크로 정의를 억제하는 트릭입니다.

http://support.microsoft.com/kb/143208


windows.h를 포함한 사람들의 경우 영향을받는 헤더에 다음을 입력하십시오.

#include windows headers ...

pragma push_macro("min")
pragma push_macro("max")
#undef min
#undef max

#include headers expecting std::min/std::max ...

...

pragma pop_macro("min")
pragma pop_macro("max")

소스 파일에서 #undef min 및 max.

#include windows headers ...

#undef min
#undef max

#include headers expecting std::min/std::max ...

windows.h가 min을 매크로로 정의한다고 가정합니다.

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

그것은 오류 메시지를 설명합니다.


To solve this issue I just create header file named fix_minmax.h without include guards

#ifdef max
    #undef max
#endif

#ifdef min
    #undef min
#endif

#ifdef MAX
    #undef MAX
#endif
#define MAX max

#ifdef MIN
   #undef MIN
#endif
#define MIN min

#include <algorithm>
using std::max;
using std::min;

Basic usage is like this.

// Annoying third party header with min/max macros
#include "microsoft-mega-api.h"
#include "fix_minmax.h"

Pros of this approach is that it works with every kind of included file or part of code. This also saves your time when dealing with code or libraries that depend on min/max macros

참고URL : https://stackoverflow.com/questions/5004858/why-is-stdmin-failing-when-windows-h-is-included

반응형