Adding the interface of a library to the private include path of another target

Hi,

is there a built-in method to add the (complete) interface of a library to the private include directories of another target (i.e. the include path used when compiling that target)?

Example:

  • lib1: non-INTERFACE_ONLY library which has header1.h in its interface
  • lib2: non-INTERFACE_ONLY library which has header2.h in its interface; header2.hcontains #include "header1.h"
  • executable: one of its .c files contains #include "header2.h"; no link dependency on lib2 or lib1

Approach:

get_target_property(lib2_interface lib2  INTERFACE_INCLUDE_DIRECTORIES)
target_include_directories(executable PRIVATE ${lib2_interface})
  • Would this work reliably? I mean:
    • regardless of the order in which the lib1, lib2, and executable targets are defined
    • transitively (pulling in also the interface of lib1 without explicitly having to specify that dependency in the executable target)
  • Is there a better method to add lib2’s (and transitively also lib1’s) interface directories to the include directories used when compiling executable?

Kind regards
Ingolf

Maybe, you can use the following pattern:

target_link_libraries(executable PRIVATE "$<COMPILE_ONLY:lib2>")

For more information, see $<COMPILE_ONLY:…> help.

1 Like

Thanks, Marc, for this hint. I had not been aware of that generator expression.

Unfortunately, we are currently more or less bound to using CMake 3.21.x, so I’d still be interested in an assessment as in my first question.