Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Undefined Reference to WSAStartup@8'

I am using Code::Blocks, MinGW, and Windows. Im trying to initialize the winsock so that I can work on a project. I keep getting the error Undefined Reference to WSAStartup@8 Anyone know how to go about fixing this?

#include <stdio.h>
#include <stdlib.h>
#include <winsock2.h>

#pragma comment(lib,"ws2_32.lib")

int main(int argc , char *argv[]){
    WSADATA wsa;
    int output;

    output=WSAStartup(MAKEWORD(2,2),&wsa);
    if(output != 0) {
        printf("Startup failed %d\n", output);
        return 1;
    } else {
        printf("Initialized");
        return 0;
    }

}
like image 284
Paulo Avatar asked Dec 20 '15 19:12

Paulo


4 Answers

Linker looks for dependencies after the code was loaded. If library appeared in the building process before the symbols were needed, because source files appeared after that, then no symbols were used and later when they appear in source files they will be unresolved. Place the winsock library -lws2_32 that you link with AFTER the source and object files.

gcc prog.c -o prog -lws2_32
like image 191
4pie0 Avatar answered Oct 17 '22 02:10

4pie0


I made another way, I find the library that contain funtion that compiler can't link to, then I add to linker of compiler. and almost of librarys are in the lib folder of MINGW (often be C:/MinGW/lib); like thisThese are libraries I add when I got some errors with Dlib Or you can do this instruction for auto regconite missing lib. Building a wxWidgets program in Code::Blocks

like image 2
Kien.VietNam Avatar answered Oct 17 '22 01:10

Kien.VietNam


Your source code shows that you use the very specific, (to Microsoft's compiler), #pragma comment(lib,"ws2_32.lib") statement. There are two problems with this:

  1. This pragma isn't valid in GCC, (i.e. MinGW compilers), so it is simply ignored, both at compile and link time.
  2. In MinGW, (in common with GCC convention on most (maybe all?) other platforms), there is no "ws2_32.lib"; the correct name for the library, (which is an import library for ws2_32.dll), is "libws2_32.a".

To resolve your issue, you must not rely on MSVC specific pragmas, in your source code; rather, you must specify the library correctly on the linking command line, (almost) as tinky_winky shows:

gcc prog.c -o prog.exe [...other .c and .o files...] -lws2_32 ...

(and ensure that any libraries you specify come after the object files, or source files, which require them).

like image 1
Keith Marshall Avatar answered Oct 17 '22 01:10

Keith Marshall


You may should check your compiler options, add -lws2_32 to add linker options when linking. I use TDM-GCC, works well after that.

like image 1
Runker Hamming Avatar answered Oct 17 '22 00:10

Runker Hamming