What is the correct way to use target_link_libraries with a static library in CMake

I am creating a library associated with a static library. I am trying to figure out a way to distribute only include, not static library libraries, when I export targets for the library that I create. Below is an example of a CMakeLists static library

cmake_minimum_required(VERSION 3.7) project(mystaticlib) set(PROJECT_SRCS ${PROJECT_SOURCE_DIR}/src/mystatic.cpp) set(PROJECT_INCS ${PROJECT_SOURCE_DIR}/include/mystatic.h) add_library(${PROJECT_NAME} STATIC ${PROJECT_SRCS} ${PROJECT_INCS}) target_include_directories(${PROJECT_NAME} PUBLIC $<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/include> $<INSTALL_INTERFACE:${CMAKE_INSTALL_PREFIX}/include>) export(TARGETS ${PROJECT_NAME} APPEND FILE ${CMAKE_BINARY_DIR}/${CMAKE_PROJECT_NAME}Targets.cmake) 

very standard and nothing special, now here are my CMakeLists libraries that link to this static library

 cmake_minimum_required(VERSION 3.7) project(testlib) set(PROJECT_SRCS ${PROJECT_SOURCE_DIR}/src/mytest.cpp) set(PROJECT_INCS ${PROJECT_SOURCE_DIR}/include/mytest.h) add_library(${PROJECT_NAME} SHARED ${PROJECT_SRCS} ${PROJECT_INCS}) target_include_directories(${PROJECT_NAME} PUBLIC $<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/include> $<INSTALL_INTERFACE:${CMAKE_INSTALL_PREFIX}/include>) target_link_libraries(${PROJECT_NAME} PRIVATE mystaticlib) # target_link_libraries(${PROJECT_NAME} PUBLIC mystaticlib) export(TARGETS ${PROJECT_NAME} APPEND FILE ${CMAKE_BINARY_DIR}/${CMAKE_PROJECT_NAME}Targets.cmake) 

The problem of target_link_libraries with PRIVATE is that inclusion directories from the static library are not exported. Therefore, external users reference testlib , it will not be able to find where the headers of the static library are.

The problem with target_link_libraries with PUBLIC is that a static library is not needed for external users. I want an external user to be able to reference testlib .

What is the correct way to solve this problem?

+5
source share

Source: https://habr.com/ru/post/1263461/


All Articles