Visual C++ - Error C2011 'sockaddr': 'struct' type redefinition
다음과 같이 간단한 코드가,
#include "stdafx.h"
#include <windows.h>
#include <winsock2.h>
int main()
{
int len = sizeof(sockaddr);
return 0;
}
컴파일하면 무수히 많은 redefinition 오류를 발생시킵니다. 검색해 보면 다음의 글에서 정확한 원인을 짚어내고 있습니다.
C++ Redefinition Header Files (winsock2.h)
; https://stackoverflow.com/questions/1372480/c-redefinition-header-files-winsock2-h
As others suggested, the problem is when windows.h is included before WinSock2.h. Because windows.h includes winsock.h. You can not use both WinSock2.h and winsock.h.
따라서, 다음과 같이 아~~~~주 다양한 해결책이 나옵니다. ^^
1) winsock2.h를 제외하거나,
#include "stdafx.h"
#include <windows.h>
// #include <winsock2.h>
int main()
{
int len = sizeof(sockaddr);
return 0;
}
2) windows.h 헤더를 포함하기 전에 _WINSOCKAPI_ 또는 WIN32_LEAN_AND_MEAN 매크로 상수를 등록하거나,
#include "stdafx.h"
#define _WINSOCKAPI_ // #define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
int main()
{
int len = sizeof(sockaddr);
return 0;
}
3) winsock2.h를 먼저 include 하거나!
#include "stdafx.h"
#include <winsock2.h>
#include <windows.h>
int main()
{
int len = sizeof(sockaddr);
return 0;
}
예제의 경우에는 단순히 sockaddr를 사용하기 때문에 위의 3가지 방법 중 어느 것이든 상관없지만, 만약 자신이 사용하려는 Windows Socket의 특정 버전이라면, 방법에 따라 어느 것(winsock.h, winsock2.h)이 포함되는지 인지를 해야 합니다.
[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]