如何将.so文件链接到cpp程序

时间:2018-01-05 14:25:39

标签: c++ ssh libssh2 .so

我的本​​地计算机上有libssh2.so.1.0.1(.so)二进制文件,我的计算机上没有任何头文件。

这是我尝试通过ssh协议连接到服务器的基本ssh程序。 参考:How to establish a simple ssh connection with c++

现在我无法将库(libssh2.so.1.0.1)链接到以下示例程序。

以下是我编写的示例程序,后面跟着错误。

sshsample.cpp:

#include <stdlib.h>
#include <stdio.h> 
int main()
{
    ssh_session my_ssh_session;
    int rc;
    int port = 22;
    int verbosity = SSH_LOG_PROTOCOL;
    char *password;
    // Open session and set options
    my_ssh_session = ssh_new();
   if (my_ssh_session == NULL)
   exit(-1);
   ssh_options_set(my_ssh_session, SSH_OPTIONS_HOST, "192.168.1.6");
   ssh_options_set(my_ssh_session, SSH_OPTIONS_USER, "john");
   ssh_options_set(my_ssh_session, SSH_OPTIONS_LOG_VERBOSITY, &verbosity);
   // Connect to server
   rc = ssh_connect(my_ssh_session);
   if (rc != SSH_OK)  
   {
    fprintf(stderr, "Error: %s\n", ssh_get_error(my_ssh_session));  
    ssh_free(my_ssh_session);
    exit(-1);
}
// Authenticate ourselves
password = "pass";
rc = ssh_userauth_password(my_ssh_session, NULL, password);
if (rc != SSH_AUTH_SUCCESS)
{
    fprintf(stderr, "Error authenticating with password: %s\n",
    ssh_get_error(my_ssh_session));
    ssh_disconnect(my_ssh_session);
    ssh_free(my_ssh_session);
    exit(-1);
    }
  ssh_disconnect(my_ssh_session);
  ssh_free(my_ssh_session);
}

我用下面的命令编译了上面的文件

g++ -L. -llibssh2 -o main sshsample.cpp

但是我收到以下错误

sshsample.cpp: In function 'int main()':
sshsample.cpp:8: error: 'ssh_session' was not declared in this scope
sshsample.cpp:8: error: expected `;' before 'my_ssh_session'
sshsample.cpp:11: error: 'SSH_LOG_PROTOCOL' was not declared in this scope
sshsample.cpp:14: error: 'my_ssh_session' was not declared in this scope
sshsample.cpp:14: error: 'ssh_new' was not declared in this scope

任何建议/帮助都会有很大用处

提前致谢...

1 个答案:

答案 0 :(得分:3)

您需要将libssh2头文件包含在调用ssh API的编译单元中。如果没有这个,你不能指望编译器解决ssh_session的问题。如果正确安装了库,则应该可以访问头文件来调用它。

#include <libssh2.h>

编辑:老实说,您在示例中使用的API属于原始libssh库,我在示例中看不到需要与libssh2链接的任何内容。

#include <libssh/libssh.h>