简体   繁体   中英

“No rule to make target” error in cmake when linking to shared library

In Ubuntu, I have downloaded a third-party shared library, mylibrary.so , which I have placed in the directory /home/karnivaurus/Libraries . I have also placed the associated header file, myheader.h , in the directory /home/karnivaurus/Headers . I now want to link to this library in my C++ code, using CMake. Here is my CMakeLists.txt file:

cmake_minimum_required(VERSION 2.0.0)

project(DemoProject)

include_directories(/home/karnivaurus/Headers)

add_executable(demo demo.cpp)

target_link_libraries(demo /home/karnivaurus/Libraries/mylibrary)

However, this gives me the error message:

:-1: error: No rule to make target `/home/karnivaurus/Libraries/mylibrary', needed by `demo'.  Stop.

What's going on?

While the other answer posted here is valid, it is out-dated. CMake now provides better solutions for using a pre-built external library in your code. In fact, CMake itself even discourages the use of link_directories() in its documentation.

The target_link_libraries() command takes very specific syntax for linking to an external library. A more modern solution is to create an IMPORTED CMake target for your external library:

add_library(MyExternalLib SHARED IMPORTED)

# Provide the full path to the library, so CMake knows where to find it.
set_target_properties(MyExternalLib PROPERTIES IMPORTED_LOCATION /home/karnivaurus/Libraries/mylibrary.so)

You can then use this imported CMake target later on in your code, and link it to your other targets:

target_link_libraries(demo PRIVATE MyExternalLib)

For other ways to use an external third-party library in your CMake code, see the responses here .

You may use a full path to the static library. To link w/ dynamic one, better to use link_directories() like this:

cmake_minimum_required(VERSION 2.0.0)

project(DemoProject)

include_directories(/home/karnivaurus/Headers)
link_directories(/home/karnivaurus/Libraries)

add_executable(demo demo.cpp)

target_link_libraries(demo mylibrary)

and make sure mylibrary has prefix lib and suffix .so in file name (ie full name is /home/karnivaurus/Libraries/libmylibrary.so ).

To make you project more flexible, you'd better to write a finder module and avoid hardcode paths like /home/karnivaurus/*

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM