General
- Use latest CMake
- Find dependecies - find_package. Be careful with add_subdirectory and FetchContent
- Prepare for
FetchContent
users - manually namespace targets, make possible to disable packaging rules. - Do not GLOB for sources.
- GenerateExportHeader - works for single library type.
- Put in
CMakeLists.txt
exactly what is necessary to produce a working build. - Portability can lead to combinatorial explosion. Consider cmake presets
Create build targets
- add_executable - create an executable target
- add_library - create a library target
Working with targets
- target_sources - add source files to target
- target_include_directories - add include directories to target
- target_compile_options - add compile options to target
- target_link_libraries - add libraries or linker flags to target
PRIVATE
,PUBLIC
,INTERFACE
Additional target properties
- target_compile_definitions
- target_compile_features
- target_link_directories
- target_link_options
- target_precompile_headers
Work with properties
- get_target_property
- set_target_properties
- function
- cmake_parse_arguments
- generator-expressions
- add_custom_command
Working with variables
- Set a normal variable
- Setting a cache entry
Module File
CMAKE_MODULE_PATH
FindOracle.cmake
file- Environment variable used
- https://github.com/SOCI/soci/blob/master/cmake/modules/FindOracle.cmake
- find_path - include path. Store result in
Oracle_INCLUDE_DIR
. mark_as_advanced to hide it from GUIs - find_library . Store result in
Oracle_LIBRARY
- find_program to find client programs.
- execute_process to call external program i.e. get the version.
- Check received variables using FindPackageHandleStandardArgs
- Create target
Oracle::Oracle
if (NOT TARGET Oracle::Oracle) add_library(Oracle::Oracle UNKNOWN IMPORTED) set_target_properties(Oracle::Oracle PROPERTIES IMPORTED_LOCATION "{Oracle_LIBRARIES}" INTERFACE_INCLUDE_DIRECTORIES "{Oracle_INCLUDE_DIRS}") endif()
- Add default include directories
C++20 modules
- import CMake; C++20 Modules
- Using CMake with C++20 modules
- Static checks with CMake/CDash - iwyu, clang-tidy, lwyu, cpplint and cppcheck
References
- import CMake: // 2023 State of C++20 modules in CMake - Bill Hoffman - CppNow 2023
- The Challenges of Implementing C++ Header Units: C++ Modules - Daniel Ruoso - CppNow 2023
- CMake: A Case Study - Hans Vredeveld - ACCU 2023
- Things I Learnt While Trying to Avoid Becoming a CMake Expert - CB Bailey - ACCU 2022
- Modern CMake Best Practices for Library Authors by Alex Reinking - San Diego C++ Meetup 7/11/2023
- SD C++ Meetup 2023
- https://github.com/alexreinking/sdcppmu-diffuse
- Building a Dual Shared and Static Library with CMake
- https://github.com/ComicSansMS/cpp_modules_includes