Anyway to automatically add include dir when using target_link_libraries?

Hi, when I wrote libraries, I was wondering is there anyway I can expose my headers automatically when someone using target_link_libraries to link my lib? Usually, when we use some libraries, even if most libraries offer some variables to hold headers’ path, we should manually write target_include_directories along with target_link_libraries.

So if I’m writing a library, is there any mechanism, so that users can automatically include headers just using target_link_libraries

1 Like

Indeed there is, the CMake term for this is “usage requirements.” It’s covered in CMake documentation which is well worth reading, but here’s a quick code sample to get you started:

# Define your library and its usage requirements:
add_library(MyLib ...)
target_include_directories(MyLib PUBLIC pub/inc1) # These will be used both by the library and by whoever links to it
target_include_directories(MyLib PRIVATE src) # These will be used only when building the library, not by its clients

Include directories (and copile definitions, and compile options, and link options, and linked libraries, …) which are specified using PUBLIC are used when building the library itself, and also added to whoever’s consuming the library. Those added with PRIVATE are used only when building the library. (And for completeness, those added with INTERFACE are added only to the consumers who link against the library, but are not used when building the library itself).

1 Like

Hi @Angew, thank very much for helping, I’m curious that why plenty of libraries I use still need to manually include headers (especially when using find_package)? Does it due to the project mixed public and private headers in the same directory?

Usage requirements other than transitive linking were first introduced to CMake in 2.8.11, and support/infrastructure for them is expanding gradually. So they are newer than a lot of projects’ CMake support, meaning those projects may be reluctant to rewrite their build specification to support them.

1 Like