Post

Include Custom CMake Modules

Lets abstract some configuration of our project to a user defined Config.cmake file.

Let’s assume your project uses CMake and has a directory structure similar to the one shown below

C++ project with directory structure with custom CMake modules

The Config.cmake file has the following stuff -

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
set_target_properties(
  ${CMAKE_PROJECT_NAME}
  PROPERTIES CXX_STANDARD 17
             CXX_STANDARD_REQUIRED YES
             CXX_EXTENSIONS NO)

include(CheckIPOSupported)
check_ipo_supported(RESULT result)
if(result)
  set_target_properties(${CMAKE_PROJECT_NAME}
                        PROPERTIES INTERPROCEDURAL_OPTIMIZATION TRUE)
endif()

find_program(CCACHE_PROGRAM ccache)
if(CCACHE_PROGRAM)
  set(CMAKE_CXX_COMPILER_LAUNCHER "${CCACHE_PROGRAM}")
  set(CMAKE_CUDA_COMPILER_LAUNCHER "${CCACHE_PROGRAM}") # CMake 3.9+
endif()

Then, in our root CMakeLists.txt file, lets add the following lines -

1
list(APPEND CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/cmake/Modules")

This line must go after your project configuration

And finally,

1
include(Config)

Where Config is the name of file with our abstractions

This post is licensed under CC BY 4.0 by the author.