如何在CMake中正确链接libssh库?编译报错求助
链接libSSH库时出现未定义引用错误的解决方法
问题场景
编译使用libSSH的C项目时遭遇链接错误,编译器提示多个libSSH核心函数未定义,具体错误信息如下:
intero@:~/Documents/projects/c/fastDeploy/build$ make Consolidate compiler generated dependencies of target deployExe [ 50%] Linking C executable deployExe/usr/bin/ld: CMakeFiles/deployExe.dir/main.c.o: in function `set_ssh_options': main.c:(.text+0x2cc): undefined reference to `ssh_options_set' /usr/bin/ld: main.c:(.text+0x2e5): undefined reference to `ssh_options_set' /usr/bin/ld: main.c:(.text+0x2fe): undefined reference to `ssh_options_set' /usr/bin/ld: CMakeFiles/deployExe.dir/main.c.o: in function `main': main.c:(.text+0x359): undefined reference to `ssh_new' /usr/bin/ld: main.c:(.text+0x3ab): undefined reference to `ssh_free' collect2: error: ld returned 1 exit status make[2]: *** [CMakeFiles/deployExe.dir/build.make:97: deployExe] Error 1 make[1]: *** [CMakeFiles/Makefile2:83: CMakeFiles/deployExe.dir/all] Error 2 make: *** [Makefile:91: all] Error 2
当前使用的CMakeLists.txt:
cmake_minimum_required(VERSION 3.2) project(fastDeploy) add_executable(deployExe main.c) find_package(LibSSH REQUIRED) target_link_libraries(deployExe PRIVATE ${LIBSSH_LIBRARIES})
系统中已找到的libSSH路径:
intero@intero-MS-7971:~/Documents/projects/c/fastDeploy$ sudo find / -name 'libssh' /usr/include/libssh /usr/lib/x86_64-linux-gnu/cmake/libssh find: ‘/tmp/.mount_nvimN16HgQ’: Permission denied
解决步骤
1. 修正CMake链接目标
新版LibSSH的CMake配置推荐使用导入目标LibSSH::libssh而非旧版的LIBSSH_LIBRARIES变量,修改CMakeLists.txt如下:
cmake_minimum_required(VERSION 3.2) project(fastDeploy) add_executable(deployExe main.c) find_package(LibSSH REQUIRED) target_link_libraries(deployExe PRIVATE LibSSH::libssh)
导入目标会自动处理头文件路径和依赖库链接,避免变量名不匹配导致的链接失败。
2. 清理CMake缓存并重新构建
如果之前的CMake缓存残留了错误配置,执行以下命令重置构建环境:
cd build rm -rf * cmake .. make
3. 确认libSSH开发包完整安装
若系统仅安装了libSSH运行时库,缺少头文件或链接库会导致此错误。在Debian/Ubuntu系系统中安装完整开发包:
sudo apt install libssh-dev
4. 修复代码中的参数错误
你的set_ssh_options函数存在常量使用错误,第三行的端口设置误用了SSH_OPTIONS_HOST,应改为SSH_OPTIONS_PORT:
void set_ssh_options(ssh_session session, ConnectionInfo *credentials) { ssh_options_set(session, SSH_OPTIONS_HOST, &credentials->host); ssh_options_set(session, SSH_OPTIONS_LOG_VERBOSITY, &credentials->verbosity); ssh_options_set(session, SSH_OPTIONS_PORT, &credentials->port); // 修正此处常量 }
此错误虽不影响编译,但会导致运行时无法正确设置SSH端口,建议一并修复。
内容的提问来源于stack exchange,提问作者intero
相关产品推荐
相关产品推荐

