I'm learning winsockets and got a linker error when calling the socket(af, type, protocol)
function in a constructor.
main.cpp
#include "Server.h"
int main(int argc, char **argv) {
nmd::Server *server = new nmd::Server();
//TODO: Logic
delete server;
server = nullptr;
return 0;
}
Server.h
#pragma once
#include <WinSock2.h>
#include <WS2tcpip.h>
namespace nmd {
class Server {
public:
Server();
virtual ~Server();
private:
SOCKET socket_;
};
}
Server.cpp
#include "Server.h"
nmd::Server::Server() {
socket_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (INVALID_SOCKET == socket_)
throw 1; // TODO: proper exception handling
}
nmd::Server::~Server() {}
When I try to build it, an unresolved external symbol error occur. In detail:
LNK2019 unresolved external symbol __imp__socket@12 referenced in function "public: __thiscall nmd::Server::Server(void)" (??0Server@nmd@@QAE@XZ)
What am I missing here? I want to know the source of this problem, not only the solution. What makes the compiler to belive that nmd::Server::Server()
is undefined when I put the socket(...)
function in it?
You need to add Ws2_32.lib
to your linker command to resolve that function.