Unresolved External Symbol C++ I need to use sockets from winsok2.h. So, I written a class NetObject to use it. But, when I do compilation I am getting an error:

error LNK2019: unresolved external symbol "public: int __thiscall wsa::NetObject::connect(void)" (?connect@NetObject@wsa@@QAEHXZ) referenced in function _main


I do this using Visual C++ compiler.

Here is some code:

//wsa.h
#ifndef WSA_H_
#define WSA_H_

#include &lt;winsock2.h&gt;

namespace wsa {

sockaddr_in init(const int, const char *, const int);
sockaddr_in init(const int, const char *);
SOCKET init(const int, const int, const int);

class NetObject {
private:
    SOCKET sock;
    sockaddr_in addr;
    int check(const int);
public:
    NetObject
        (
            const int addr_family,
            const int sock_type,
            const int protocol,
            const char * ip_addr,
            const int port
        ): sock(init(addr_family, sock_type, protocol)),
           addr(init(addr_family, ip_addr, port)) {};
    int connect();
};
}

#endif //WSA_H_

//wsa.cpp
#include "wsa.h"
#include &lt;winsock2.h&gt;

namespace wsa {

sockaddr_in init(const int af, const char * ip_addr) {
    sockaddr_in addr;
    memset(&amp;addr, 0, sizeof(addr));
    addr.sin_family = af;
    addr.sin_addr.s_addr = inet_addr(ip_addr);
    return addr;
}

sockaddr_in init(const int af, const char * ip_addr, const int port) {
    sockaddr_in addr = init(af, ip_addr);
    addr.sin_port = htons(port);
    return addr;
}

SOCKET init
    (
        const int af,
        const int type,
        const int protocol
    ) {

    SOCKET s;
    s = socket(af, type, protocol);
    while (s == INVALID_SOCKET) {
        if (closesocket(s) == SOCKET_ERROR) {
            return INVALID_SOCKET;
        }
        s = socket(af, type, protocol);
    }
    return s;
}

inline int NetObject::check(const int code) {
    if (code == SOCKET_ERROR) {
        if (closesocket(sock) == SOCKET_ERROR)
            return 1;
        return SOCKET_ERROR;
    }
    return 0;
}

inline int NetObject::connect() {
    int res = ::connect(sock, (sockaddr *)&amp;addr, sizeof(addr));
    return check(res);
}   
}

//main.cpp
#include "wsa.h"
#include &lt;winsock2.h&gt;

const int af       = AF_INET;
const int type     = SOCK_STREAM;
const int protocol = IPPROTO_TCP;

int main(int argc, char * argv[]) {

    WSADATA ws;
    if (WSAStartup(MAKEWORD(2, 0), &amp;ws) == -1) {
        return 1;
    }

    wsa::NetObject server(af, type, protocol, argv[1], 80);
    server.connect();
    WSACleanup();
}


I can't see any errors. Please, help!
Thats because in Visual Studio, including winsock2.h to your headers is not enough. You have to tell the Linker your project will need the library wsock32.lib.

You can do that either by editing the properties of your project, or by including this line to your code:

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