1

I'm using QT Creator to build a C plain project. My project inlcudes a socket creation and I'm getting many errors of reference.

My code is simple:

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

// Need to link with Ws2_32.lib
#pragma comment (lib, "Ws2_32.lib")

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

    printf("\nInitialising Winsock...");
    if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
    {
        printf("Failed. Error Code : %d",WSAGetLastError());
        return 1;
    }

    printf("Initialised.\n");

    if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET)
    {
        printf("Could not create socket : %d" , WSAGetLastError());
    }

    printf("Socket created.\n");

    return 0;
}

Compilation errors:

undefined reference to `_imp__WSAStartup@8'
undefined reference to `_imp__WSAGetLastError@0'
undefined reference to `_imp__socket@12'
undefined reference to `_imp__WSAGetLastError@0'

Then I suppose this means that winsock2.h lib is not included. How to do this without #pragma comment()?

Alexandre Thebaldi
  • 4,546
  • 6
  • 41
  • 55

1 Answers1

2

Your #include <winsock2.h> usage is fine. It's that you need to update your project settings and add ws2_32.lib as a link library.

For Qt, just add this line to your .pro file. Assumes you are using a Microsoft compiler:

LIBS += ws2_32.lib

Note: I had to actually delete the "build" directory from the command line and then do a "clean build" from Qt Creator for the change to take effect.

selbie
  • 100,020
  • 15
  • 103
  • 173