Unable to link libssh in Cmake

I am trying to compile C++ Qt app that needs a connection to a ssh server, but I am unable to do it, as every time I try to compile it, I am getting the following error code:

[1/1] Linking CXX executable SSH-Manager
FAILED: SSH-Manager 
: && /usr/bin/c++ -g  CMakeFiles/SSH-Manager.dir/SSH-Manager_autogen/mocs_compilation.cpp.o CMakeFiles/SSH-Manager.dir/src/main.cpp.o CMakeFiles/SSH-Manager.dir/src/mainwindow.cpp.o CMakeFiles/SSH-Manager.dir/src/ssh_connection.cpp.o -o SSH-Manager  -Wl,-rpath,/home/<username>/Qt/6.4.1/gcc_64/lib:  -L  -lssh  /home/<username>/Qt/6.4.1/gcc_64/lib/libQt6Widgets.so.6.4.1  /home/<>username/Qt/6.4.1/gcc_64/lib/libQt6Gui.so.6.4.1  /home/<username>/Qt/6.4.1/gcc_64/lib/libQt6Core.so.6.4.1  /usr/lib/x86_64-linux-gnu/libGL.so && :
/usr/bin/ld: CMakeFiles/SSH-Manager.dir/src/ssh_connection.cpp.o: in function `SSH_connection::SSH_connection()':
/home/<username>/Programming/Projects/SSH-Manager/src/ssh_connection.cpp:11: undefined reference to `ssh_new'

/usr/bin/ld: /home/<username>/Programming/Projects/SSH-Manager/src/ssh_connection.cpp:17: 
collect2: error: ld returned 1 exit status
ninja: build stopped: subcommand failed.

And the relevant part of CMakeLists.txt:

    target_link_libraries(SSH-Manager PRIVATE -L${LIBSSH_LIBRARY} -lssh)
else ()
    message(Unable to find libssh!)
endif ()

What have I already tried:

  1. purged and reinstalled openssh-server and libssh-dev
  2. found and verified libssh.h file
  3. included LIBSSH_DIR

What am I doing wrong?

>Solution :

If you look at what is being passed to the compiler, the error becomes pretty clear:

... -Wl,-rpath,/home/<username>/Qt/6.4.1/gcc_64/lib:  -L  -lssh 

As you can see -L is empty.

To fix this let’s start with the correct usage of target_link_libraries, this is NOT the correct usage:

target_link_libraries(SSH-Manager PRIVATE -L${LIBSSH_LIBRARY} -lssh)

Do not pass anything like -Lxxx -lxxx to this function, the function doesn’t serve as a function that passes compiler options. If you check the libssh site you will see the variables which are populated, i.e. find_package(package) populates certain variables that you then can use in your CMakeLists.txt, in your case you are mainly interested in ${LIBSSH_LIBRARIES}, also note that you shouldn’t need to use link_directories(). So instead of

target_link_libraries(SSH-Manager PRIVATE -L${LIBSSH_LIBRARY} -lssh)
# it should look like this
target_link_libraries(SSH-Manager PRIVATE ssh) #OR ${LIBSSH_LIBRARIES}

Also bare in mind that the name of the package might be case-sensitive if you are on Linux

EDIT: The authors also have an alias, so target_link_libraries(project ssh) is sufficient. Check the link provided to see the correct usage of it in your project.

Leave a Reply