Lorac Lorac - 2 months ago 11
C++ Question

Using an utilities library (headers-only) in multiple modules with cmake

I have this kind of arborescence:

Project
CMakeList.txt
-- Module 1
CMakeList.txt
-- include
-- src
CMakeList.txt
-- Module 2
-- ...
-- utilities (Headers Only - It will have .cpp probably later)
-- include
-- typedefs.h
-- ..


I would like to be able to use my Utilities library into any modules.
I've tried using

https://cmake.org/cmake/help/v3.6/command/add_library.html#interface-libraries

My Utilities cmakelist.txt

project(Utilities LANGUAGES CXX)


When I try to include into my cpp files

#include "utilities/include/typedefs.h"


It cannot find the file. I've tried with : (doesn't work)

#include "include/typedefs.h"
#include "typedefs.h"


I'm trying to find what do I need to do into my module CMakeList.txt files so that the compiler can find the #include statement.

The top level has :

...
add_subdirectory(utilities)
add_subdirectory(Module1)
add_subdirectory(Module2)
..


I added into the top-level cmakelist.txt : (doesn't work)

include_directories("${Utilities_SOURCE_DIR}/include")


I do not have to link it yet, since there is not .cpp file. I just need to be able to #include into the different modules.

Answer

You should use target_include_directories along with your target.
As an example:

target_include_directories(my_target PUBLIC "${Utilities_SOURCE_DIR}/include")

Then, all the source files that belong to the target my_target will be able to access to the headers as:

#include <typedefs.h>

Use relative paths otherwise.

Comments