在MinGW上隐式声明函数’getaddrinfo’
我有一个使用getaddrinfo()
的C程序。 它在Linux和Mac OS X上按预期工作。
我正在将它移植到Windows。
当我编译它(使用MinGW gcc)时,我收到以下警告:
ext/socket/socket.c: In function 'sl_tcp_socket_init': ext/socket/socket.c:98:5: warning implicit declaration of function 'getaddrinfo' [-Wimplicit-function-declaration] ext/socket/socket.c:104:9: warning implicit declaration of function 'freeaddrinfo' [-Wimplicit-function-declaration]
然后整个事情无法链接到getaddrinfo()
和freeaddrinfo()
未定义引用。
现在,根据这个MSDN页面 ,Windows上支持getaddrinfo()
,它位于头文件Ws2tcpip.h
和库文件Ws2_32.lib
。
我包括Ws2tcpip.h
并与-lWs2_32
链接,所以我不确定为什么这不起作用。
如果您查看ws2tcpip.h的第297行,可以看到_WIN32_WINNT的值已经检查过。
#if (_WIN32_WINNT >= 0x0501) void WSAAPI freeaddrinfo (struct addrinfo*); int WSAAPI getaddrinfo (const char*,const char*,const struct addrinfo*, struct addrinfo**); int WSAAPI getnameinfo(const struct sockaddr*,socklen_t,char*,DWORD, char*,DWORD,int); #else /* FIXME: Need WS protocol-independent API helpers. */ #endif
在你的包含之前只需#define _WIN32_WINNT
。
如果要在编译器范围内创建代码,实际上还应该使用与NTDDI_VERSION
相同的OS版本定义_WIN32_WINNT
。 如果没有这个定义,只有_WIN32_WINNT
不允许你使用getaddrinfo()
和一些编译器(即Watcom)。 最好以与Windows SDK相同的方式包装它:
#define _NTDDI_VERSION_FROM_WIN32_WINNT2(ver) ver##0000 #define _NTDDI_VERSION_FROM_WIN32_WINNT(ver) _NTDDI_VERSION_FROM_WIN32_WINNT2(ver) #ifndef _WIN32_WINNT # define _WIN32_WINNT 0x501 #endif #ifndef NTDDI_VERSION # define NTDDI_VERSION _NTDDI_VERSION_FROM_WIN32_WINNT(_WIN32_WINNT) #endif
据说解决这个问题的正确方法是:
#define WINVER WindowsXP
或者更明智地将-DWINVER=WindowsXP
添加到您的CPPFLAGS
。
参考: http : //mingw.5.n7.nabble.com/Undefined-reference-to-getaddrinfo-td5694.html
注意:然而,对我来说不起作用。