C - Undefined Reference to WSAStartup@8'

Paulo picture Paulo · Dec 20, 2015 · Viewed 26.7k times · Source

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

}

Answer

4pie0 picture 4pie0 · Dec 20, 2015

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