今天练习Windows网络编程,从书上拷了一段最简单的Windows Socket API测试代码来运行:
#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
void main(int argc, char* argv[])
{
WSADATA wsaData;
int Ret;
// Initialize Winsock version 2.2
if ((Ret = WSAStartup(MAKEWORD(2,2), &wsaData)) != 0)
{
// NOTE: Since Winsock failed to load we cannot use
// WSAGetLastError to determine the specific error for
// why it failed. Instead we can rely on the return
// status of WSAStartup.
printf("WSAStartup failed with error %d/n", Ret);
return;
}
// Setup Winsock communication code here
// When your application is finished call WSACleanup
if (WSACleanup() == SOCKET_ERROR)
{
printf("WSACleanup failed with error %d/n", WSAGetLastError());
}
}
编译成功了,链接时却报错,提示_imp__WSAStartup, _imp__WSACleanup, _imp__WSAGetLastError等标识符的定义找不到。 查看VC目录,该程序所需的winsock2.h和WS2_32.LIB文件都在。
后来在VC中把WS2_32.LIB以手工方式添加到项目中才正常通过(打开 Project -> Settings -> Link -> Object/Library Modules,把WS2_32.LIB添加到最后)。
不知其它lib是否都需要加在Project -> Settings -> Link -> Object/Library Modules中。