Menu

#2133 undefined reference to WSAStartup

WSL
closed
nobody
None
Support
self-service
Behaves_as_Documented
False
2014-12-18
2013-11-11
atar
No

Hi there!

I'm trying to write a winsock2 application and according to the MSDN site
it should be done with the following:

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include <stdio.h>

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

int main() {

                        WSADATA wsaData;

                        int iResult;

// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
if (iResult != 0) {
                          printf("WSAStartup failed: %d\n", iResult);
                          return 1;
}
                        return 0;
}

the problem is that the linker says that the WSAStartup() function isn't
defined (undefined reference to `WSAStartup@8).

what's the problem here?

the environment is:

CodeBlocks (IDE).

Shell: cmd.exe.

Compiler version: gcc version 4.7.1 (tdm-1).

Regards!

atar.

Discussion

  • RichB

    RichB - 2014-12-18

    the problem is that the linker can't find the library. Delete the pragma line with "Ws2_32.lib". In CodeBlocks, click on Project, Build Options, Linker Settings, and add a reference to libws2_32.a.

     
  • Keith Marshall

    Keith Marshall - 2014-12-18

    You do not need to delete the pragma; you do need to be aware that in GCC -- the compiler provided by MinGW.org -- #pragma comment(...) is just that ... a comment. It does not produce the linking side effect that it does in MSVC; thus you must instruct the linker explicitly, in the linking command, to search supplementary libraries; you cannot do this via pragmas embedded in source translation units.

    Also, please note that MinGW.org does not offer usage support for CodeBlocks, (nor any other IDE), nor for compilers which we do not distribute ourselves ... such as the TDM variant noted on the original ticket.

     
  • Keith Marshall

    Keith Marshall - 2014-12-18
    • status: unread --> closed
    • Resolution: none --> self-service
    • Category: Unknown --> Behaves_as_Documented
     
MongoDB Logo MongoDB