cmake Design Pattern

Overview

This is a description of the cmake CMakeLists.txt overall structure.

skeleton

The overall layout of the CMakeLists.txt file is:

<...global declarations here...>

# === project: proj1
project(proj1)
add_executable(${CMAKE_PROJECT_NAME})
target_source(${CMAKE_PROJECT_NAME} PRIVATE file1.cpp ...)
target_include_directories(${CMAKE_PROJECT_NAME} PRIVATE dir1 ...)
target_compile_option(${CMAKE_PROJECT_NAME} PRIVATE opt1 ...)

# === project: proj2
project(proj2)
add_executable(${CMAKE_PROJECT_NAME})
target_source(${CMAKE_PROJECT_NAME} PRIVATE file1.cpp ...)
target_include_directories(${CMAKE_PROJECT_NAME} PRIVATE dir1 ...)
target_compile_option(${CMAKE_PROJECT_NAME} PRIVATE opt1 ...)

<...other projects...>
  • project() - declares a project and automatically sets ${CMAKE_PROJECT_NAME}. Use ${CMAKE_PROJECT_NAME} for all commands related to that project otherwise it will be applied globally
  • add_executable() - defines the project is an executable. This has to be defined before the target_xx() commands.
  • target_source() - declares the source files needed for this project
  • target_include_directories() - declares the include directories (if any)
  • target_compile_option() - declares the compilation options for this executable

Other commands:

  • add_library() - if you are defining a library, not an executable
  • compilation related:

    • target_precompile_headers() - causes the listed header files to be precompiled
    • target_compile_definitions() - used for -D for preprocessor definitions
    • target_compile_features() - used to define a "feature". see Compile Features
  • link related:

    • target_link_libraries() - list of libraries to link into the executable
    • target_link_directories() - list of directories to search for libraries to link in
    • target_link_options() - link options for thi executable

- John Arrizza