Awesome
Modern CMake Examples
Update (2024/10/14)
I've written a book about CMake! 😱
It's called Minimal CMake and is going to be published on January 3rd, 2025 by Packt. You can find a (non-affiliate) link to the book on amazon.co.uk here, and amazon.com here.
There's a full accompanying repo for the book available here that you're more than welcome to check out to get an idea about the content of the book. I'd be delighted if you'd like to order a copy and I hope it will prove as useful as this repo has turned out to be. This repo was very much the inspiration for the book, and if it wasn't for all the stars and support I don't think it would have happened.
A huge thank you to everyone who starred the repo, it means a huge amount!
Overview
This repository is a collection of as simple as possible CMake projects (with a focus on installing). The idea is to try and help understand exactly what each part of a CMakeLists.txt
file does and why it is needed.
This is basically intended as a series of reminders to help me remember how to use CMake 🤦
Please see the Core Example README for steps on using the example libraries and the Installing README for an overview of installing CMake libraries. The More Example section contains slightly more complex examples and will continue to grow.
Disclaimer
I am NOT a CMake expert - these examples may contain gaffs, faux pas, mistakes etc etc.. Please take everything with a pinch of salt and if you recognize a blatant error or mistake please feel free to create an issue or PR.
Background
For the longest time I just didn't grok installing in CMake<sup>1</sup>.
I didn't understand why you'd ever want to do it, or what it was useful for. When I started looking into how to do it, I could not make head nor tail of all the various install commands. While trying to figure all this stuff out I was immersing myself in trying to learn Modern CMake (targets, targets targets...) and how these two things are related.
The examples in this repo are the culmination of many months of sporadic research to try and understand CMake more fully and write better CMake scripts.
I'm sharing my journey so far to hopefully help some other poor soul who is in the same boat I'm in. With any luck there will be something someone finds useful here.
For an explanation<sup>2</sup> of what (in the context of CMake) installing is, please see the installing section and take a look at the various example projects for context.
- I recently discovered a kindred spirit on reddit
- My interpretation?
Miscellaneous
While using CMake over the last several months I've stumbled across a few useful little bits and bobs that I feel are worth recording/sharing.
Less cd
-ing
To run CMake from your source directory (instead of having to mkdir build && cd build
) you can pass -S
and the path to your source folder (most likely just .
for where you currently are) and -B
to specify the build folder.
cd <project/root>
cmake -S . -B build/
You then just need to remember to call
cmake --build build/
to actually build your project.
Note: The
-S
option was added to CMake in version3.13
. Before then you could use the undocumented-H
option. I'd recommend sticking with-S
now if you can 🙂.
compile_commands.json
You should absolutely use -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
when generating your project to have CMake create a compile_commands.json
file for you. This is useful for all sorts of tools (clang-tidy
, cppcheck
, oclint
, include-what-you-use
etc. etc...).
# when configuring from the root CMakeLists.txt of your project
cmake -S . -B build/ -DCMAKE_EXPORT_COMPILE_COMMANDS=ON
Note:
CMAKE_EXPORT_COMPILE_COMMANDS
is only supported for Make and Ninja generators. The good news is it's pretty simple to use Ninja on Windows in place of Visual Studio/MSBuild - for instructions please see this repo.TLDR: Add
-G Ninja
to the above command to use Ninja.
Defines
Sometimes it's really useful to be able to set defines at the command line when running the CMake generator. An easy way to do this is to add a simple generator expression to your CMakeLists.txt
file in target_compile_definitions
.
target_compile_definitions(
${PROJECT_NAME} PRIVATE
$<$<BOOL:${YOUR_DEFINE}>:YOUR_DEFINE>)
In your code you can then use this define for some sort of conditional compilation.
#ifdef YOUR_DEFINE
// something useful
#endif // YOUR_DEFINE
And when invoking cmake
you can pass a CMake variable like so if you want that macro to be defined.
# from the src/ (root) folder
cmake -S . -B build/ -DYOUR_DEFINE
If you don't pass the variable then the generator expression will evaluate to false and no define will be added.
Extra Output
Sometimes when building with CMake to diagnose an issue you might want more info about exactly what's being compiled. You can see everything that's passed to the compiler when building with the --verbose
(-v
) flag.
# from the src/ (root) folder
cmake --build build/ -v
This works for an array of generators (Make, Visual Studio, Ninja etc.).
CONFIG
You'll notice all the find_package
commands include the CONFIG
keyword after the package name (and REQUIRED
). This is to let CMake know we're explicitly using a CMake <package>-config.cmake
file and not a FindModule command (all these examples use the more modern config approach so including CONFIG
in the find_package
command should be preferred).
DEBUG_POSTFIX
It is possible to set a property called DEBUG_POSTFIX
on a given target to have a string appended to the name of the debug version of the library (usually d
or -debug
, but as far as I know it can be anything).
set_target_properties(
${PROJECT_NAME} PROPERTIES DEBUG_POSTFIX "d")
This is incredibly useful when installing libraries as it means if you build and install the Debug
configuration and then build and install the Release
configuration, the Debug
version of the library won't be overridden (you'll just have your-libraryd.lib
and your-library.lib
) in the lib/
folder. This works for single and multi-config generators.
FetchContent
Check out the fetch-content example for a simple demonstration using the commands and see the links below by Sascha Offe, Kuba Sejdak and Michael Hirsch for more information.
ExternalProject_Add
Check out the external-project-add example for an (opinionated) introduction on how to take advantage of the command.
cmake-helpers
I've put together some little wrappers to reduce the amount of boilerplate needed when installing libraries. These can be pulled in using FetchContent
. Please see cmake-helpers for more details.
Project Structure
When creating a library that is going to be used via installing (find_package
) and/or add_subdirectory
/FetchContent
, it is wise to ensure the include paths for files are the same for both. For this reason it's (in my humble opinion) best to format your directory structure like so:
|-- <library-name>/
|-- include/
|-- <library-name>/
|-- file1.h
|-- file2.h
|-- etc...
|-- src/
|-- file1.cpp
|-- file2.cpp
|-- etc...
|-- CMakeLists.txt
When you specify target_include_directories
(see below), have it point to the include/
folder so all includes wind up looking like #include "library-name/file1.h"
as opposed to just #include "file1.h"
. This helps to compartmentalize the library files (similar to a namespace
).
target_include_directories(
${PROJECT_NAME}
INTERFACE $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>)
The install command for the interface (.h
) files then looks like this:
install(DIRECTORY ${CMAKE_CURRENT_LIST_DIR}/include/${PROJECT_NAME}
DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME})
Now the include paths for the library will always be consistent whether using find_package
or FetchContent
.
Aside: For more information on approaches to project structure checkout out Pitchfork by vector-of-bool.
CMake Resources
I've been attempting to learn CMake for a while and have built up quite a list of articles/blogs/documentation that have helped inform my understanding up to this point. Please see them listed below (mainly for my benefit so I have them all in one place).
Articles
- CLIUtils
- The Coding Nest
- Pablo Arias
- steveire
- GitLab.Kitware - CMake
- Foonathan
- Coderwall
- Arne Mertz
- rix0r
- Crascit
- Mario Badr
- mbinna
- LLVM
- devdocs
- Jetbrains - CLion
- SysProgs - visualgdb
- ecrafter
- KDAB
- Cognitive Waves
- Reddit - How to CMake good
- Fosdem - Alexander Neundorf
- fede.tft
- Daniel Pfeifer
- kde
- Schneide Blog - Marius Elvert
- Jeff Preshing
- Sam Thursfield
- Sascha Offe
- Kuba Sejdak
- Michael Hirsch, Ph.D.
- Siliceum - Clément Grégoire
Documentation
- cmake-buildsystem
- cmake-packages
- cmake-properties
- cmake-generator-expressions
- install
- find_package
- target_include_directories
- target_compile_definitions
- project
- macro
- function
- set
- ExternalProject
- FetchContent
- CMakePackageConfigHelpers
- CMAKE_PREFIX_PATH
- CMAKE_INSTALL_PREFIX
- CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT
Stack Overflow
- How to use CMake to find and link to a library using install-export and find_package?
- preferred cmake project structure
- CMake: How to set up source, library and CMakeLists.txt dependencies?
- CMake share library with multiple executables
- Setting CMAKE_INSTALL_PREFIX from CMakeLists.txt file
- Modern way to set compiler flags in cross-platform cmake project
- cmake usefulness of aliases
- Package vs Library
- After CMake install, I can't find a package with find_package
- cmake add_library, followed by install library destination
- CMake install is not installing libraries on Windows
- How to copy DLL files into the same folder as the executable using CMake?
- Path to target output file
- Building of executable and shared library with cmake, runtimelinker does not find dll
- https://stackoverflow.com/questions/28692896/how-to-use-cmake-generator-expression-target-filetgt
- A simple example of using cmake to build a Windows DLL
- CMake run custom command before build?
- How to change the build type to Release mode in cmake?
YouTube
- Oh No! More Modern CMake - Deniz Bahadir - Meeting C++ 2019
- More Modern CMake - Deniz Bahadir - Meeting C++ 2018
- CppCon 2019: Craig Scott “Deep CMake for Library Authors”
- C++Now 2017: Daniel Pfeifer “Effective CMake"
- CMake for Dummies
- C++Now 2018: Mateusz Pusz “Git, CMake, Conan: How to Ship and Reuse our C++ Projects”
- CppCon 2017: Mathieu Ropert “Using Modern CMake Patterns to Enforce a Good Modular Design”
- Embracing Modern CMake
- C++ Weekly - Ep 78 - Intro to CMake
- How to CMake Good - Recommended Order
Books
- Professional CMake: A Practical Guide
- CMake Cookbook: Building, testing, and packaging modular software with modern CMake
- Mastering CMake (I haven't read this personally)
Other
- Cpplang Slack #cmake channel
- There's some super helpful people on there, the search functionality is great too (someone likely will have had your problem before 😉).
- vector-of-bool
- Was incredibly kind in answering some of my dumb CMake questions - thank you!