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;
}
}
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
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
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:
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).
You may should check your compiler options
, add -lws2_32
to add linker options when linking
.
I use TDM-GCC, works well after that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With