#include 'stdafx.h' #include <windows.h> #include <winsock.h> #include <stdio.h> int APIENTRY WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR IpCmdLine,int nCmdShow) { WSADATA ws; char buf[100]; WSAStartup(0x0101,&ws); sprintf(buf,'%d.%d',HIBYTE(ws.wVersion),LOBYTE(ws.wVersion)); MessageBox(0,buf,'info',0); WSACleanup(); return 0; }
This program is for getting information of available wsock version in the computer. I cannot understand why ‘stdafx.h’ is included in program. What’s the significance of APIENTRY? Can’t we use _stdcall instead? I also can’t compile it in VC++. What’s the problem with the code?
Below are the errors when executing program there are no errors during compiling.
--------------------Configuration: sa - Win32 Debug-------------------- Linking... sa.obj : error LNK2001: unresolved external symbol _WSACleanup@0 sa.obj : error LNK2001: unresolved external symbol _WSAStartup@8 LIBCD.lib(crt0.obj) : error LNK2001: unresolved external symbol _main Debug/sa.exe : fatal error LNK1120: 3 unresolved externals Error executing link.exe. sa.exe - 4 error(s), 0 warning(s)
stdafxis used to implement precompiled headers in VC++. You can put your library headers like windows.h and winsock.h, etc.. in there and they will only be compiled once each time you modify stdafx.h.APIENTRY is usually just a define for __stdcall, but sometimes it is defined blank (if __stdcall is not supported for example). It’s to make your code more portable.
Without the actual errors you are getting, I’m not going to be able to help much. But my first guess is that you have unicode on in your build and it’s complaining that MessageBoxW doesn’t take a char[100] as an argument. In this case, either use wide chars everywhere, or turn off unicode, or use MessageBoxA to explicitly use the ASCII version.
Edit:
Now with the errors, it’s easy. Under Project properties -> Linker -> Input -> Additional Dependencies, add ws2_32.lib. So you can get the Winsock functions linked in.
The missing _main indicates that you are building the app as a console app, and not a windows app. Go back to project Properties -> Linker -> System and set SubSystem to Windows (/Subsystem:Windows) instead of Console. Or else, just rename WinMain to
int main()(Make sure you drop the APIENTRY).Also, if you’re using MSVC++ you might as well use the safer sprintf_s: