c++visual-studio-2015nugetlibssh2

Referencing libssh2 in C++ project using NuGet package throws a linker error


I am looking into using the libssh2 library for a project I am working on in C++. I have created a very basic project to test it, before I implement it properly in my main app.

I have taken an example from https://www.libssh2.org/examples/direct_tcpip.html and I have installed the libssh2 library using the NuGet Package Manager in Visual Studio 2015.

I have the following code

#include <libssh2.h>
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>

using namespace std;

const char *username = "user";
const char *password = "password";
const char *server_ip = "127.0.0.1";
const char *local_listenIP = "127.0.0.1";
unsigned int local_listenport = 2222;
const char *remote_desthost = "127.0.0.1";
unsigned int remote_destport = 22;
enum {
    AUTH_NONE = 0,
    AUTH_PASSWORD,
    AUTH_PUBLICKEY
};

int main()
{
    int rc, i, auth = AUTH_NONE;

    struct sockaddr_in sin;
    socklen_t sinlen;
    const char *fingerprint;
    char *userauthlist;
    LIBSSH2_SESSION *session;
    LIBSSH2_CHANNEL *channel = NULL;
    const char *shost;
    unsigned int sport;
    fd_set fds;
    struct  timeval tv;
    ssize_t len, wr;
    char buf[16384];
    char sockopt;
    SOCKET sock = INVALID_SOCKET;
    SOCKET listenSocket = INVALID_SOCKET, forward_socket = INVALID_SOCKET;
    WSADATA wsadata;
    int err;

    err = WSAStartup(MAKEWORD(2, 0), &wsadata);
    if (err != 0)
    {
        cout << "WSAStartup failed with error " << err << " Msg: " << strerror(err) << endl;
        return EXIT_FAILURE;
    }
rc = libssh2_init(0);
    if (rc != 0)
    {
        cout << "Failed to init libssh2. Error " << rc << " Msg: " << strerror(err) << endl;
        return EXIT_FAILURE;
    }

When it compiles I get the following errors:

Unresolved external symbol libssh2_init referenced in function main
Unresolved external symbol _imp_WSAStartup referenced in function main

Solution

  • For the first error, I agree with harmic, you can add the .lib file manually to your project to resolve the libraries link failed: Add .lib file: Properties>Linker->Input->Additional Dependencies, Add the .lib file path: Properties>Linker->General->Additional Dependencies.

    For the Second error, The problem is you are not linking against the Ws2_32.lib library. To fix this you can add following code to the source file of your project.

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