How to force target_link_libraries to link only dependency, no additional include directories?

Here minimal example:

cmake_minimum_required(VERSION 3.17 FATAL_ERROR)

project(foo)

add_library(lib1 OBJECT lib1/lib1.cpp lib1/lib1.hpp)
target_include_directories(lib1 PUBLIC lib1)

add_library(lib2 OBJECT lib2/lib2.cpp lib2/lib2.hpp)
target_link_libraries(lib2 PRIVATE lib1)
target_include_directories(lib2 PUBLIC lib2)

add_executable(foo main.cpp)
target_link_libraries(foo PRIVATE lib2 lib1)

Because of cmake bug object library dependecies do not propagate, so I have to specify dependency of foo to lib1 manually: target_link_libraries(foo PRIVATE lib2 lib1) or I get link time error.

But this also populate include directory list, so source files of foo after target_link_libraries(… lib1) can no access include from lib1 directory. I do not want this.

So can I somehow only link lib1 with foo, and do not pull new include paths from lib1 to foo ?

You almost have the answer in your headline: LINK_ONLY
target_link_libraries(foo PRIVATE lib2 $<LINK_ONLY:lib1>)

And it’s not a CMake bug, it’s a feature :wink: or better said, a design decision.

1 Like