Reference error in winsock2

Asked

Viewed 147 times

0

I am wanting to create a socket in c with the windows api winsock2.h but while trying to compile my code returns me the following error

Undefined referrence to Wsastartup

Undefined referrence to Wsagetlast

Error error: Ld returned 1 Exit status

Winsock startup code

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

#pragma comment(lib,"ws2_32.lib") //Winsock Library

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

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

    printf("Initialised.");

    return 0;
}

1 answer

1

1) Remove this line of code

#pragma comment(lib,"ws2_32.lib") //Winsock Library

2) In Codeblocks IDE, enter a new project, I named it Sockets CodeBlocks

3) Choose Console Application and click GO

In the window that appears click on Next and then choose the language C CodeBlocks

4) In the main. c function put your code without using #pragma

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

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

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

    printf("Initialised.");

    return 0;
}

5) Right-click on the project name and choose Build Options Build Options

6) Choose (Click) the Linker Settings tab and Link Libraries click the ADD button Linker Settings

7) Type the following: ws2_32 and click OK inserir a descrição da imagem aqui

8) Compile and see that you are error free now compilando socket

9) When executing appears the message in a good now! Bom Estudo!!! inserir a descrição da imagem aqui Note: If it is in another IDE see how to insert the blioteca because the GCC compiler often does not recognize or consider inclusions of bilbioteca via #pragma directive

Browser other questions tagged

You are not signed in. Login or sign up in order to post.