using winsock

Hi! Just started winsock using the tutorial on MSDN... here's where I am so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif

#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iostream>

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

using namespace std;

int main(int argc, char** argv)
{
	WSADATA wsaData;
	
	int iResult;
	
	// Initialize Winsock
	
	iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
	
	if(iResult != 0)
	{
		cout << "WSAStartup failed: " << iResult;
		
		return 1;
	}
	
	system("pause");
	
	return 0;
}


When I try to compile the code, I get the following error message:

\winsock\main.o main.cpp:(.text+0x24): undefined reference to `__imp_WSAStartup'

It's my first time programming a windows app and I'm using orwell dev-cpp... anyone knows what's going on?

Thanks,
AeonFLux

You need to link with library ws2_32.lib.
closed account (13bSLyTq)
Hi,

@kbw is correct once again.

I'd like to expand upon it as Richard Feynman once said "I learned the difference between knowing the name of something and knowing something" so I'd like to explain why this fails.

The reason this fails because MSDN is an Microsoft websites (very obvious) and since Microsoft have developed the well-known IDE and compiler Visual C++ they use the VC++ working code and in VC++ the developer can tinker with the project settings (linking being case here) in-code and the way they can do this is by using the #pragma directive and since directives depend on the compiler, I conclude #pragma comment() is an VC++ only directive and since Orwell Dev-Cpp is not an VC++ compiler type but rather an MingW based it will not work.


The #pragma comment(lib, "Ws2_32.lib") is an way of telling the VC++ compiler to link with library ws2_32.lib so on VC++ it does this, and the code will work but unfortunately since Orwell Dev-Cpp does not have this capability you must perform this task manually by linking Ws2_32.lib to the project. Then it will successfully execute and work!

I hope this helps & good luck on your endeavors,
OrionMaster
Thanks for the input guys, you're both right! I tried to link ws2_32.lib at first only to find that it wasn't on the computer... then I downloaded it, tried to link it without success... I found the answer here :

http://www.tinkerforge.com/en/doc/Software/API_Bindings_C.html

It was suggested on this site that the winsock2 library was in the lib file libws2_32.a

I found this file in the mingw32 lib directory in dev-cpp, linked it and all is working perfectly!

Thanks again,
AeonFlux
Topic archived. No new replies allowed.