gpt4 book ai didi

c++ - 对 `__imp_WSACleanup' 的 undefined reference

转载 作者:可可西里 更新时间:2023-11-01 14:55:31 25 4
gpt4 key购买 nike

这是我使用 winsock 的第一个程序。如您所见,我有 #include <winsock2.h>并链接 ws2_32.dll ,但代码仍然无法编译:

#include<winsock2.h>
#pragma comment(lib, "ws2_32")
class CInitSock{
public:

CInitSock(BYTE minorVer=2,BYTE majorVer=2){
//initialize WS2_32.dll
WSADATA wsaData;
WORD sockVersion = MAKEWORD(minorVer,majorVer);
if(::WSAStartup(sockVersion,&wsaData)!=0){
exit(0);
}
}
//release winSock libary
~CInitSock(){
::WSACleanup();
}
};

#include "CInitSock.h"
#include<stdio.h>
CInitSock initSock;
int main(void){
char szHost[256];
::gethostname(szHost,256);
hostent *phost = ::gethostbyname(szHost);
in_addr addr;
for(int i = 0;;i++){
char *p = phost->h_addr_list[i];
if(p==NULL){
break;
}
memcpy(&addr.S_un.S_addr,p,phost->h_length);
char *szIp = ::inet_ntoa(addr);
printf("%s \n",szIp);
}
}

这是错误:

mingw32-make.exe -f "D:\project\c_program\Makefile.win" all
g++.exe GetAllIPs.o -o win_socket.exe -L"D:/tools/develepment/Dev-Cpp/MinGW64/x86_64- w64-mingw32/lib" -L"D:/tools/develepment/Dev-Cpp/MinGW64/lib32" -static-libgcc -mwindows -g3


GetAllIPs.o: In function `main':
D:\project\c_program/GetAllIPs.cpp:6: undefined reference to `__imp_gethostname'
D:\project\c_program/GetAllIPs.cpp:7: undefined reference to `__imp_gethostbyname'
D:\project\c_program/GetAllIPs.cpp:15: undefined reference to `__imp_inet_ntoa'
GetAllIPs.o: In function `CInitSock::CInitSock(unsigned char, unsigned char)':
D:\project\c_program/CInitSock.h:10: undefined reference to `__imp_WSAStartup'
GetAllIPs.o: In function `CInitSock::~CInitSock()':
D:\project\c_program/CInitSock.h:16: undefined reference to `__imp_WSACleanup'
collect2.exe: error: ld returned 1 exit status

mingw32-make.exe: *** [win_socket.exe] Error 1

现在我完全糊涂了...

最佳答案

您使用的 pragma 仅适用于 Visual C++ 编译器,将被 gcc 忽略

#pragma comment(lib, "ws2_32")

您必须在 makefile 中手动添加 ws2_32.lib。喜欢:

-L"ws2_32"

(我猜它最后没有“.lib”)

在 g++ 行的末尾。您当然已经添加了我目前还没有的完整路径。

关于c++ - 对 `__imp_WSACleanup' 的 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18559028/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com