如何在C中正确包含libssh

时间:2019-01-19 09:57:04

标签: c gcc libssh

每次尝试在Ubuntu上使用gcc编译代码时,都会出错。

我通过输入以下命令安装了libssh-dev:

sudo apt-get install libssh-dev

它安装得很好(没有错误消息)

我要编译的代码是:

#include <stdlib.h>
#include <stdio.h>
#define LIBSSH_STATIC 1
#include <libssh/libssh.h>

int main(void){
    int rc;
    int port = 21;
    char *pass = "password";

    ssh_session my_ssh_session = ssh_new();
    if(my_ssh_session == NULL){
        exit(-1);
    }

    ssh_options_set(my_ssh_session, SSH_OPTIONS_HOST, "localhost");
    ssh_options_set(my_ssh_session, SSH_OPTIONS_PORT, &port);
    ssh_options_set(my_ssh_session, SSH_OPTIONS_USER, "username");

    rc = ssh_connect(my_ssh_session);
    if(rc != SSH_OK){
        fprintf(stderr, "Error connecting to localhost: %s\n", ssh_get_error(my_ssh_session) );
        exit(-1);
    } 

    ssh_userauth_password(my_ssh_session, NULL, pass);

    ssh_disconnect(my_ssh_session);
    ssh_free(my_ssh_session);
}

当我尝试编译代码时,错误消息显示:

user@neodym:~/Desktop/projects/ssh$ gcc -lssh ssh_client.c 
/tmp/ccGihId0.o: In function `main':
ssh_client.c:(.text+0x2a): undefined reference to `ssh_new'
ssh_client.c:(.text+0x57): undefined reference to `ssh_options_set'
ssh_client.c:(.text+0x6c): undefined reference to `ssh_options_set'
ssh_client.c:(.text+0x84): undefined reference to `ssh_options_set'
ssh_client.c:(.text+0x90): undefined reference to `ssh_connect'
ssh_client.c:(.text+0xa5): undefined reference to `ssh_get_error'
ssh_client.c:(.text+0xe2): undefined reference to `ssh_userauth_password'
ssh_client.c:(.text+0xee): undefined reference to `ssh_disconnect'
ssh_client.c:(.text+0xfa): undefined reference to `ssh_free'
collect2: error: ld returned 1 exit status

我都准备好用谷歌搜索,但到目前为止没有任何效果。

libssh头文件已安装在 / usr / include / libssh / 中,因此gcc应该能够找到这些文件。

您能帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

尝试使用:

gcc -c ssh_client.c

,然后通过以下方式链接到ssh库:

gcc -o ssh_client ssh_client.o -lssh

或一步:

gcc -o ssh_client ssh_client.c -lssh
相关问题