20

This is my first program with winsock. As you can see, I've #include <winsock2.h> and linked ws2_32.dll, but the code still doesn't compile:

#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);   
    }
}

This is the error:

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

Now I'm totally confused...

4

5 回答 5

27

您使用的编译指示仅适用于 Visual C++ 编译器并且会被 gcc 忽略

#pragma comment(lib, "ws2_32")

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

-L"ws2_32"

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

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

于 2013-09-01T13:51:53.523 回答
14

我和你遇到了同样的问题。我通过添加命令解决了它-lwsock32。您可以按照以下步骤添加命令:

  1. 工具
  2. 编译器选项
  3. 选择general
  4. 点击add the following commands when calling the compilers

然后你可以添加上面的命令-lwsock32

于 2017-12-16T12:37:22.823 回答
9

添加

-lwsock32

到您的命令行而不是在使用MinGW#pragma编译时

g++ src/main.cpp -o release/myApp.exe -lwsock32
于 2018-02-12T01:16:53.707 回答
6

在 DevC++ 中,导航到Project >> Project Options(或通常通过ctrl+ h);然后在“参数”选项卡中有一个按钮“添加库或对象”,然后添加libws2_32.a

于 2015-05-25T02:32:21.403 回答
3

对于 wnidows 下的代码块:转到

项目 -> 构建选项 -> 链接器设置(确保在左侧选择项目,而不是构建目标)并在左侧列表中添加(输入)库“ws2_32” 在此处输入图像描述

于 2020-10-18T16:30:55.257 回答