Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inherit include directories from used library in CMake

Tags:

cmake

If I have a library with public header files which are used by another library's public header files how can I expose the former library's public header directory to a third application which depends only from the latter library without explicitly adding the former library's header files' path to the application's target_include_directories section?

I know this is a bit confusing, here is a simple example:

I have two shared libraries and one application in the same cmake project:

  • library_foo has a directory which contains its public header files
  • library_bar has also a directory with its public header files. One of these public header files (lib_bar/bar.h) contains an #include <lib_foo/foo.h> entry, i.e. the public header file has a reference to a public header file defined in library_foo.
  • library_bar implementation depends on library_foo.
  • app depends directly only on the library_bar.
  • app's main.cpp contains an #include <lib_bar/bar.h>.

So, app depends indirectly from library_foo and its header files as well.

I would like to write three CMakeLists.txt files for these three parts of my application. In the CMakeLists.txt of app I would like to specify dependency only to library_bar, i.e. the library and header dependecies from libarary_foo which are specified in library_bar CMakeLists.txt must be transferred to app. How can I do this? I would like to use target_* solution.

like image 364
Tibor Takács Avatar asked Oct 16 '22 21:10

Tibor Takács


1 Answers

Command target_include_directories is used exactly for the purpose of inheritance:

add_library(library_foo SHARED ...)
# Include directories are made an interface of 'foo'.
target_include_directories(library_foo PUBLIC <dir-with-lib_foo/foo.h>)


add_library(library_bar SHARED ...)
target_include_directories(library_bar PUBLIC <dir-with-lib_bar/bar.h>)
# Linking with 'foo' propagates include directories
# and makes these directories an interface of 'bar' too.
target_link_libraries(library_bar library_foo)


add_executable(app ...)
# Application will use include directories both from 'bar' and 'foo'.
target_link_libraries(app library_bar)
like image 106
Tsyvarev Avatar answered Oct 21 '22 00:10

Tsyvarev