Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined reference to `__imp_WSACleanup'

Tags:

c++

c

winsock2

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...

like image 336
user2682541 Avatar asked Sep 01 '13 13:09

user2682541


2 Answers

The pragma you use only works for the Visual C++ Compiler and will be ignored by the gcc

#pragma comment(lib, "ws2_32")

you have to add the ws2_32.lib it manually in the makefile. like:

-L"ws2_32"

(I guess it was without the ".lib" at the end)

at the end of the g++ line. You have of course add the full path which I have not by hand at the moment.

like image 105
Martin Schlott Avatar answered Sep 20 '22 15:09

Martin Schlott


I met the same problem with you. I solved it by adding a command -lwsock32. you can add the command according follow steps:

  1. tools
  2. compiler options
  3. choose general
  4. click add the following commands when calling the compilers

then you can add the above command -lwsock32.

like image 20
L.ling Avatar answered Sep 20 '22 15:09

L.ling