Friday, September 2, 2022

[SOLVED] Cmake - Add files from other sub-projects

Issue

Let's say I have two sub-projects: A and B

This is my root CMakeLists.txt

cmake_minimum_required (VERSION 3.8)

project ("Project")

add_subdirectory ("A")
add_subdirectory ("B")

In /B I have file test.h

How can I include /B/test.h in A ?

I have tried to add target_include_directories(B) in /A/CMakeLists.txt but it does not seem to work


Solution

When you write add_subdirectory(B) (quotes are not necessary), you must have a CMakeLists.txt in the directory B.

This CMakeLists.txt may have the following content:

add_library(targetB INTERFACE)
target_include_directories(targetB INTERFACE ${CMAKE_CURRENT_SOURCE_DIR})

These 2 lines create a CMake target called targetB with the INTERFACE property. This is very handy for header only library. All cmake target that links with targetB will then include the CMAKE_CURRENT_SOURCE_DIR with is the directory A where your test.h is.

Then, you have add_subdirectory(A) with a CMakeLists.txt that may look like this (assuming you have a main in this dir A):

add_executable(foo ${CMAKE_CURRENT_SOURCE_DIR}/main.c)
target_link_libraries(foo PRIVATE targetB)

Then second line create the relation between the target foo and the target targetB and, when compiling, the path to your test.h will be set in the command line.



Answered By - Martin
Answer Checked By - Clifford M. (WPSolving Volunteer)