在 Windows 上链接库 Libssh 时尝试编译 c++ 程序时出现以下错误(软件包 libssh-common 和 libssh-devel 均随 cygwin 安装)。Clion 没有给出包含错误,并且 cmake 在 Clion 的 Cmake 重新加载期间找到了该库,但在编译/链接时,它会抱怨引用未定义。
有人能指出我的愚蠢错误吗?提前谢谢!
Scanning dependencies of target main
[ 50%] Building CXX object CMakeFiles/main.dir/main.cpp.o
[100%] Linking CXX executable main.exe
CMakeFiles/main.dir/main.cpp.o:main.cpp:(.text+0x30): undefined reference to `ssh_new'
CMakeFiles/main.dir/main.cpp.o:main.cpp:(.text+0x30): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `ssh_new'
collect2: error: ld returned 1 exit status
我的 CmakeLisst.txt
add_executable(main main.cpp)
find_package(LIBSSH)
IF (LIBSSH_FOUND)
message(${LIBSSH_VERSION})
include_directories(${LIBSSH_INCLUDE_DIR})
link_directories(${LIBSSH_INCLUDE_DIR})
target_link_libraries(main ${LIBSSH_LIBRARIE})
endif ()
输出 Cmake 重新加载
C:\Users\seven\.CLion2018.3\system\cygwin_cmake\bin\cmake.exe -DCMAKE_BUILD_TYPE= -DCMAKE_MAKE_PROGRAM=C:/cygwin64/bin/make.exe -DCMAKE_C_COMPILER=C:/cygwin64/bin/gcc.exe -DCMAKE_CXX_COMPILER=C:/cygwin64/bin/g++.exe -G "CodeBlocks - Unix Makefiles" "/cygdrive/c/Users/seven/Documents/github/Server control"
0.7.5
-- Configuring done
-- Generating done
-- Build files have been written to: /cygdrive/c/Users/seven/Documents/github/Server control/cmake-build-default-cygwin
[Finished]
主程序
#include <stdlib.h>
#include <iostream>
#define LIBSSH_STATIC 1
#include <libssh\libssh.h>
int main() {
std::cout << "Hello world" << std::endl;
ssh_session my_ssh_session = ssh_new();
return 0;
}
--更新 1-- CmakeOutput.log github要点
- 解决方案 - -
必须将我的 cmakelist 更改为以下内容
find_package(LIBSSH)
IF (LIBSSH_FOUND)
message(${LIBSSH_VERSION})
include_directories(${LIBSSH_INCLUDE_DIR})
link_directories(${LIBSSH_LIBRARY_DIR})
target_link_libraries(main -L${LIBSSH_LIBRARY} -lssh)
endif ()
答案1
从make VEBOSE=1
输出来看,libssh 库确实没有链接。
尝试修复 CMakeLists.txt 中的以下行:
link_directories(${LIBSSH_LIBRARY_DIR})
target_link_libraries(main ${LIBSSH_LIBRARY})
- 参数应该
link_directories
是LIBSSH_LIBRARY_DIR
,而不是LIBSSH_INCLUDE_DIR
。 - 参数应该
target_link_libraries
是LIBSSH_LIBRARY
,而不是LIBSSH_LIBRARIE
。
或者,另外一种方式:
link_directories(${LIBSSH_LIBRARY_DIR})
target_link_libraries(main -L${LIBSSH_LIBRARY_DIR} -lssh")