• Check Cmake version using cmake --version
  • Add comments using #
  • Variables are accessed using ${VARIABLE_NAME} which is similar to bash scripting
  • mark_as_advanced ensures that variable doesn’t show up in GUIs unless show advanced is ON
    • option() does something similar more succinctly
cmake_minimum_required(VERSION 3.12...3.28)
 
if(${CMAKE_VERSION} VERSION_LESS 3.12)
	cmake_policy(VERSION ${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION})
endif()

This is pretty useful! It supports a range of CMake versions while also using the better settings. This is especially helpful when I’m focusing on backward compatibility without sacrificing modern behaviour

project(project_name VERSION 1.0
					 DESCRIPTION "nice project"
					 LANGUAGES CXX)

This line comes next. You describe

  • The name of your project
  • The version number of your project
  • A simple description of your project
  • The programming language of your project’s code

Add executable

add_executable(exe_name target_name source_files_names)
  • exe_name - The name of the executable you want to create
  • target_name - Name of CMake target generated
  • source_files_names - A list of all the source files and headers to compile with the target

Header Files

Header files will be ignored by CMake here. They are here only for them to show up in IDEs. CMake will compile source file extensions

Targets

target_include_directories(lib_name PUBLIC include)

This adds info about the include files the executable requires

  • PUBLIC{Library} - Any targets that link to this target must require include
  • PRIVATE - Only affect current target, not dependency
  • INTERFACE - Only needed for dependencies
add_library(lib_name STATIC some_other_sources)
target_link_libraries(exe_name PUBLIC lib_name)
graph LR

A["lib"]
B["exe"]

A -->|linked to| B
  • Some source files are added to lib
  • lib is now linked to exe

add_library()

  • This makes a library that your project will use
  • I’ll ignore STATIC for now. I don’t get what this does yet

Source: CMake Basics