[CMake] Recursively include target include directories only

Robert Dailey rcdailey.lists at gmail.com
Wed Jun 17 19:43:06 EDT 2015


On Wed, Jun 17, 2015 at 4:31 PM, Dan Liew <dan at su-root.co.uk> wrote:
> On 17 June 2015 at 12:28, Robert Dailey <rcdailey.lists at gmail.com> wrote:
>> Is there a way to only take (recursively) the include directiories from
>> a target or set of targets? I know that include directories propagate
>> when passing targets to target_link_libraries(), but I do not want to
>> link the libs; I only want the include directories.
>>
>> How can I do this? Thanks.
>
> I presume recursively you mean propagating the required include
> directories between targets rather anything to do recursively handling
> directories.
>
> As you mentioned include directories do propagate but this only
> happens under certain conditions (when using PUBLIC or INTERFACE
> scopes).
>
> I don't know of a way of doing it without target_link_libraries but if
> it is necessary for you to do this it sounds like you have bigger
> problems relating to the way you have your project header files
> organised.
>
> The approach I use for include directories is to have all includes for
> the project rooted in a single include directory in the source tree
> and have all includes relative to that directory. Then if I you
>
> ```
> include_directories(${CMAKE_SOURCE_DIR}/include)
> include_directories(${CMAKE_BINARY_DIR}/include) # for generated header files
> ```
>
> in the root of the project you never need to set include paths
> anywhere else for sources that are in your project tree. E.g. if there
> is header file in
>
> ${CMAKE_SOURCE_DIR}/include/project/moduleA/interface.h
>
> then in the sources this is included as
>
> #include "project/moduleA/interface.h"
>
> (note there are never relative header file includes).
>
> This is the approach that the LLVM project uses which is very simple
> and very clean (take a look at the sources). This also works very well
> for installing your header files, the contents of ${CMAKE_SOURCE_DIR}
> just need to be copied into /usr/include .

Thanks, I will go through this and see if it helps.

The reason I'm asking this question is because of how I handle unit
tests in CMake right now. Instead of just defining an executable
target for the test and then adding a link dependency on the library
containing the class or set of classes to be tested, I am manually
pulling in the CPP and H file into the test target and building them
inline with the test code. This is to support mocking (I can't mock
objects already compiled into a static library). As such, I need the
transitive includes and defines, but I do not want the transitive link
libraries.

If there is a better structure or overall approach I'm happy to
listen! This has been a nightmare so far.


More information about the CMake mailing list