简体   繁体   中英

Require shared library with dependencies in cmake

I'm new to cmake, so I'm having trouble figuring out how to model the following: My program requires a third party library that I only have access to in the form of headers and *.so files. It also ships many of its dependencies as *.so files. How do I make sure that everything compiles and links correctly, ideally in the "correct" cmake way?

I've tried this

cmake_minimum_required (VERSION 3.8)
project ("Test")

add_executable (MyApp "MyApp.cpp")
link_directories("/path/to/lib")
target_include_directories(MyApp PUBLIC "/path/to/headers")

This compiles but fails at the linking stage.

Then I tried

cmake_minimum_required (VERSION 3.8)
project ("Test")
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
add_executable (MyApp "MyApp.cpp")
find_package(Library REQUIRED)
target_link_libraries(MyApp PUBLIC Library::Library)

And cmake/FindLibrary.cmake following https://pabloariasal.github.io/2018/02/19/its-time-to-do-cmake-right/ (truncated):

...
if(Library_FOUND AND NOT TARGET Library::Library)
    add_library(Library::Library SHARED IMPORTED)
    set_target_properties(Library::Library PROPERTIES
        INTERFACE_INCLUDE_DIRECTORIES "${Library_INCLUDE_DIR}"
    )
    set_target_properties(Library::Library PROPERTIES
        IMPORTED_LOCATION "/path/to/library.so"
    )
endif()

This compiles and links, but the required other *.so files are not found at runtime. I suppose I need to add them also as libraries somehow, although I don't want them to be exported in FindLibrary.cmake . How do I do this correctly?

You can use IMPORTED libraries:

add_library(externalLib SHARED IMPORTED GLOBAL)
set_property(TARGET externalLib PROPERTY IMPORTED_LOCATION "/path/to/lib.so")
target_include_directories(externalLib INTERFACE "/path/to/headers")
target_link_directories(externalLib INTERFACE /path/to/libs)
target_link_libraries(externalLib INTERFACE -ldep1 -ldep2)

Then you can just depend on it:

target_link_libraries(MyApp PRIVATE externalLib)

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