I have a CMake project in C++ and I have been struggling how to setup the CMakeLists.txt files properly. In the external
folder there are some dependencies located, which are added to the root CMakelists.txt
by the add_subdirectory
command. It is important to mention that Project_B needs Project_A. Here is the simplified version of the folder structure:
$ tree
.
├── external
│ ├── Project_A
| ├──include
| ├── project_A.h
│ ├── projectA_0.cpp
│ └── CMakeLists.txt
|
| ├── Project_B
| ├──include
| ├── project_B.h
│ ├── projectB_0.cpp
│ └── CMakeLists.txt
|
├── root_0.cpp
├── root_1.cpp
└── CMakeLists.txt
Here is the simplified root CMakeLists.txt
# root CMakeLists.txt
cmake_minimum_required(VERSION 3.19)
project(foo)
add_subdirectory(external/Project_A)
add_subdirectory(external/Project_B)
add_executable(${PROJECT_NAME} root_0.cpp
root_1.cpp)
target_include_directories(${PROJECT_NAME} PUBLIC
external/Project_A/include
external/Project_B/include)
target_link_libraries(${PROJECT_NAME} PUBLIC
project_a
project_b)
Here is the CMakeLists.txt
of Project_A
, which is also a dependency for Project_B
. I decided to create a config.cmake file for this project and import it by Project_B
.
# Project_A CMakeLists.txt
cmake_minimum_required(VERSION 3.19)
project(project_a)
target_include_directories(${PROJECT_NAME} PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>
)
add_library(${PROJECT_NAME} STATIC projectA_0.cpp)
export(TARGETS ${PROJECT_NAME}
NAMESPACE project_a::
FILE ${CMAKE_SOURCE_DIR}/project_a_Config.cmake )
and here is the CMakeLists.txt
of Project_B
.The project_a_Config.cmake
is loaded with the help of find_package()
function. The path of the include dir from A is written in the project_a_Config.cmake
. However, I can not make those headers included properly. Should I use a *.cmake.in file?
# Project_B CMakeLists.txt
cmake_minimum_required(VERSION 3.19)
project(project_b)
add_library(${PROJECT_NAME} STATIC projectB_0.cpp)
find_package(project_a CONFIG REQUIRED HINTS ../)
target_include_directories(${PROJECT_NAME} PUBLIC
include
project_a::project_a )
target_link_libraries(${PROJECT_NAME} PUBLIC
project_a )
If there are any further problems with the structure or the used functions, just let me know! Thank you!