undefined reference to `__imp_WSAStartup‘

在windows下使用winsock2.h库的时候出现下面的问题:

net.cpp:(.text+0x2f): undefined reference to `__imp_WSAStartup'
net.cpp:(.text+0x48): undefined reference to `__imp_socket'
net.cpp:(.text+0x93): undefined reference to `__imp_inet_addr'
net.cpp:(.text+0xaa): undefined reference to `__imp_htons'
net.cpp:(.text+0xcc): undefined reference to `__imp_bind'
net.cpp:(.text+0x120): undefined reference to `__imp_listen'
net.cpp:(.text+0x189): undefined reference to `__imp_inet_ntoa'
net.cpp:(.text+0x1c9): undefined reference to `__imp_accept'
net.cpp:(.text+0x1f3): undefined reference to `__imp_inet_ntoa'
net.cpp:(.text+0x221): undefined reference to `__imp_closesocket'

解决方式是编译的时候设置-lwsock32参数,比如:

g++ net.cpp -lwsock32 -o net
#include <iostream>
#include <WinSock2.h>
#include <signal.h>


using std::cout;
using std::endl;

// 注意编译的时候需要使用 -lwsock32 命令

const int PORT = 8080;
const int QUEUE_SIZE = 20;

int main(){
  WORD	wVersionRequested;
  WSADATA wsaData;
  wVersionRequested	=	MAKEWORD(2,2);
  WSAStartup(wVersionRequested, &wsaData);
  int sd = socket(AF_INET, SOCK_STREAM, 0);
  if (sd == -1){
    cout << "create socket err"<<endl;
    return -1;
  }
  sockaddr_in addr;
  addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
  addr.sin_family = AF_INET;
  addr.sin_port = htons(PORT);

  int r = bind(sd, (sockaddr*)&addr, sizeof(addr));
  if (r == -1){
    cout << "bind socket err"<<endl;
    return -1;
  }

  if (listen(sd, QUEUE_SIZE)==-1){
    cout << "listen socket err"<<endl;
    return -1;
  }

  cout << "INFO: "<<"listen on: " << inet_ntoa(addr.sin_addr)<<":"<<PORT<<endl;
  while(true){
    sockaddr_in addr;
    int length = sizeof(addr);
    int s = accept(sd, (sockaddr*)&addr, &length);
    cout << "deal with socket: "<< inet_ntoa(addr.sin_addr)<<":"<<ntohs(addr.sin_port)<<endl;
    closesocket(s);
  }

  WSACleanup();

  return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值