SlideShare a Scribd company logo
CMake: Best Practices
Henry Schreiner
Software & Computing Roundtable 2021-2-2
Links:
The book:
My blog:
The workshop:
This talk:
launch
launch binder
binder
cliutils.gitlab.io/modern-cmake
iscinumpy.gitlab.io
hsf-training.github.io/hsf-training-cmake-webpage
gitlab.com/CLIUtils/modern-cmake-interactive-talk
Intro to CMake
In [ ]: cmake --version
What is CMake?
Is it a build system?
Build system example (Rake):
# 01-rake/Rakefile
task default: [:hello_world] do # hello_world.c
puts 'All built' # ↓
end # hello_world
# ↓
file hello_world: ['hello_world.c'] do |t| # default task
sh "gcc #{t.prerequisites.join(' ')} -o #{t.name}"
end
In [ ]: (cd 01-rake && rake)
Features:
Understands when to build/rebuild
Doesn't understand how to build
Generic; can be used for anything
Examples
make : Classic, custom syntax
rake : Ruby make
ninja : Google's entry, not designed to be hand written
Build system generator
Understands the files you are building
System independent
You give relationships
Can find libraries, etc
CMake is two-stage; the configuration step runs CMake, the build step runs a build-system
( make , ninja , IDE, etc).
Aside: Modern CMake can run the install step directly without
invoking the build system agian.
Build system generator example (CMake):
# 01-rake/CMakeLists.txt
cmake_minimum_required(VERSION 3.11)
project(HelloWorld)
add_executable(hello_world hello_world.c)
In [ ]: cmake -S 01-rake -B 01-build
cmake --build 01-build
C/C++ Examples
cmake : Cross-platform Make (also Fortran, CUDA, C#, Swift)
scons : Software Carpentry Construction (Python)
meson : Newer Python entry
basel : Google's build system
Other languages often have their own build system (Rust, Go, Python, ...)
We will follow common convention and call these "build-
systems" for short from now on
Why CMake?
It has become a standard
Approximately all IDEs support it
Many libraries have built-in support
Integrates with almost everything
Custom Buildsystems are going away
for CMake (note: C++17 only too)
Boost is starting to support CMake at a reasonable level along with BJam
Standout: Google is dual supporting Bazel and CMake
Qt 6 dropped QMake
Custom Buildsystems are going away
for CMake (note: C++17 only too)
Boost is starting to support CMake at a reasonable level along with BJam
Standout: Google is dual supporting Bazel and CMake
Qt 6 dropped QMake
Recent highlights
Thrust just received a major CMake overhaul
TBB / Intel PSTL nicely support CMake in recent years
Pybind11's CMake support was ramped up in 2.6
(More) Modern CMake
CMake is a new language to learn (and is a bit odd)
Classic CMake (CMake 2.8, from 2009) was ugly and had problems, but that's not
Modern CMake!
Modern CMake and !
CMake 3.0 in 2014: Modern CMake begins
CMake 3.1-3.4 had important additions/fixes
CMake 3.12 in mid 2018 completed the "More Modern CMake" phase
Current CMake is 3.19 (2.20 in rc2 phase)
Eras of CMake
Classic CMake: Directory based
Modern CMake: Target based
More Modern CMake: Unified target behavior
CURRENT: Powerful CLI
More Modern CMake
Best Practice: Minimum Version is important!
CMake has a (AFAIK) unique version system.
If a file start with this:
Then CMake will set all policies (which cover all behavior changes) to their 3.0 settings. This
in theory means it is extremely backward compatible; upgrading CMake will not break or
change anything at all. In practice, all the behavior changes had very good reasons to
change, so this will be much buggier and less useful than if you set it higher!
cmake_minimum_required(VERSION 3.0)
You can also do this:
Then
CMake < 3.4 will be an error
CMake 3.4 -- 3.11 will set 3.4 policies (feature was introduced in 3.12, but syntax is
valid)
CMake 3.12 -- 3.14 will set current policies
CMake 3.15+ will set 3.14 policies
cmake_minimum_required(VERSION 3.4...3.14)
Don't: set this low without a range - it will harm users. Setting < 3.9 will break IPO,
for example. Often in a way that can't be fixed by superprojects.
Do: set the highest minimum you can (build systems are hard/ugly enough as it is)
Do: test with the lowest version version you support in at least one job.
Don't: expect a CMake version significanly older than your compiler to work with it
(expecially macOS/Windows, or CUDA).
What minimum to choose - OS support:
3.4: The bare minimum. Never set less.
3.7: Debian old-stable.
3.10: Ubuntu 18.04.
3.11: CentOS 8 (use EPEL or AppSteams, though)
3.13: Debian stable.
3.16: Ubuntu 20.04.
3.18: pip
3.19: conda-forge/chocolaty/direct download, etc. First to support Apple Silicon.
What minimum to choose - Features:
3.8: C++ meta features, CUDA, lots more
3.11: IMPORTED INTERFACE setting, faster, FetchContent, COMPILE_LANGUAGE in
IDEs
3.12: C++20, cmake --build build -j N , SHELL: , FindPython
3.14/3.15: CLI, FindPython updates
3.16: Unity builds / precompiled headers, CUDA meta features
3.17/3.18: Lots more CUDA, metaprogramming
Best Practice: Running CMake
The classic method:
The modern method is cleaner and more cross-platform-friendly:
(CMake 3.14/3.15) supports -v (verbose), -j N (threads), -t target , and more
mkdir build
cd build
cmake ..
make
cmake -S . -B build
cmake --build build
Example options:
In [ ]: cmake --build 01-build -v
PUBLIC PRIVATE
INTERFACE
PUBLIC
Public Library
Main Library
Private Library
Interface Library
Target: mylibrary
Target: myprogram
Best Practice: Use Targets
Excutables and libraries are targets
Properties include:
Header include directories
Compile flags and definitions
Link flags
C++ standard and/or compiler features required
Linked libraries
Note that other things include properties, like files (such as LANGUAGE), directories, and
global
Tips for packaging
Do: use targets.
Don't: use common names for targets if you want to be used in subdirectory mode.
Don't: write a FindPackage for your own package. Always provide a PackageConfig
instead.
Export your targets to create a PackageTargets.cmake file. You can write a
PackageConfig.cmake.in ; you can recreate / reimport package there (generally use a
shared X.cmake file instead of doing it twice).
Don't: hardcode any system/compiler/config details into exported targets. Only from
shared code in Config, or use Generator expressions.
Never allow your package to be distributed without the config files!
Using other projects
1. See if the project provides a <name>Config.cmake file. If it does, you are good to
go!
2. If not, see if CMake for it built-in. If it does, you are good to
go!
3. If not, see if the authors provide a Find<name>.cmake file. If they do, complain
loudly that they don't follow CMake best practices.
4. Write your own Find<name>.cmake and include in in a helper directory. You'll need
to build IMPORTED targets and all that.
5. You can also use FindPkgConfig to piggy back on classic pkg-config.
provides a Find package
Best Practice: Handling remote dependencies
CMake can download your dependencies for you, and can integrate with files. It supports
composable (sub-)projects: One project can include another
Does not have namespaces, can cause target collisions!
Build time data and project downloads: ExternalProject (classic)
Configure time downloads FetchContent (new in 3.11+)
You can also use submodules (one of my favorite methods, but use with care)
You can also use Conan.io's CMake integration
FetchContent
FetchContent
02-fetch/hello_fmt.cpp
#include <fmt/format.h>
int main() {
fmt::print("The answer is {}n", 42);
return 0;
}
02-fetch/CMakeLists.txt
cmake_minimum_required(VERSION 3.14)
project(HelloWorld LANGUAGES CXX)
include(FetchContent)
FetchContent_Declare(
fmt
GIT_REPOSITORY https://github.com/fmtlib/fmt.git
GIT_TAG 5.3.0)
FetchContent_MakeAvailable(fmt) # Shortcut from CMake 3.14
add_executable(hello_world hello_fmt.cpp)
target_link_libraries(hello_world PRIVATE fmt::fmt)
target_compile_features(hello_world PRIVATE cxx_std_11)
In [ ]: cmake -S 02-fetch -B 02-build
cmake --build 02-build
Conan.io's conan-cmake
Conan.io has a nice CMake integration tool. It should support binaries too, since Conan.io
supports them! You must have conan installed, though - I'm using conan from conda-forge.
It works with old versions of CMake, as well.
cmake_minimum_required(VERSION 3.14)
project(HelloWorld LANGUAGES CXX)
# Conan bootstrap
if(NOT EXISTS "${CMAKE_BINARY_DIR}/conan.cmake")
message(
STATUS
"Downloading conan.cmake from https://github.com/conan-io/cmake-conan")
file(DOWNLOAD "https://github.com/conan-io/cmake-conan/raw/v0.16.1/conan.cmake"
"${CMAKE_BINARY_DIR}/conan.cmake")
endif()
include("${CMAKE_BINARY_DIR}/conan.cmake")
conan_check(REQUIRED)
conan_cmake_run(
REQUIRES fmt/6.1.2
BASIC_SETUP CMAKE_TARGETS
BUILD missing)
You can also make a conanfile.txt and manage all your dependencies there.
add_executable(hello_world hello_fmt.cpp)
target_link_libraries(hello_world PRIVATE CONAN_PKG::fmt)
target_compile_features(hello_world PRIVATE cxx_std_11)
In [ ]: cmake -S 02b-conan -B 02b-build -DCMAKE_BUILD_TYPE=Release
cmake --build 02b-build
Best Practice: Use IMPORTED targets for things you don't
build
Now (3.11+) can be built with standard CMake commands!
Can now be global with IMPORTED_GLOBAL
You'll need to set them back up in your Config file (place in one common location for
both CMakeLists and Config).
add_library(ExternLib IMPORTED INTERFACE)
# Classic # Modern
set_property( target_include_directories(
TARGET ExternLib INTERFACE /my/inc
ExternLib )
APPEND
PROPERTY
INTERFACE_INCLUDE_DIRECTORIES
/my/inc
)
Best Practice: Use CUDA as a language
Cuda is now a first-class language in CMake! (3.9+) Replaces FindCuda.
project(MY_PROJECT LANGUAGES CUDA CXX) # Super project might need matching? (3.14 at least)
# Or for optional CUDA support
project(MY_PROJECT LANGUAGES CXX)
include(CheckLanguage)
check_language(CUDA)
if(CMAKE_CUDA_COMPILER)
enable_language(CUDA)
endif()
Much like you can set C++ standards, you can set CUDA standards too:
if(NOT DEFINED CMAKE_CUDA_STANDARD)
set(CMAKE_CUDA_STANDARD 11) # Probably should be cached!
set(CMAKE_CUDA_STANDARD_REQUIRED ON)
endif()
Much like you can set C++ standards, you can set CUDA standards too:
if(NOT DEFINED CMAKE_CUDA_STANDARD)
set(CMAKE_CUDA_STANDARD 11) # Probably should be cached!
set(CMAKE_CUDA_STANDARD_REQUIRED ON)
endif()
You can add files with .cu extensions and they compile with nvcc. (You can always set the
LANGUAGE property on a file, too). Separable compilation is a property:
set_target_properties(mylib PROPERTIES
CUDA_SEPERABLE_COMPILATION ON)
New for CUDA in CMake 3.18 and 3.17!
A new CUDA_ARCHITECTURES property
You can now use Clang as a CUDA compiler
CUDA_RUNTIME_LIBRARY can be set to shared
FindCUDAToolkit is finally available
I rewrote the CUDA versions support in 3.20 to be more maintainable and more
accurate.
Best Practice: Check for Integrated Tools First
CMake has a lot of great tools. When you need something, see if it is built-in first!
Useful properties (with CMAKE_* variables, great from the command line_:
INTERPROCEDURAL_OPTIMIZATION : Add IPO
POSITION_INDEPENDENT_CODE : Add -fPIC
<LANG>_COMPILER_LAUNCHER : Add ccache
<LANG>_CLANG_TIDY
<LANG>_CPPCHECK
<LANG>_CPPLINT
<LANG>_INCLUDE_WHAT_YOU_USE
Useful modules:
CheckIPOSupported : See if IPO is supported by your compiler
CMakeDependentOption : Make one option depend on another
CMakePrintHelpers : Handy debug printing
FeatureSummary : Record or printout enabled features and found packages
Using clang-tidy in GitHub Actions example .github/workflow/format.yml :
on:
pull_request:
push:
jobs:
clang-tidy:
runs-on: ubuntu-latest
container: silkeh/clang:10
steps:
- uses: actions/checkout@v2
- name: Configure
run: cmake -S . -B build -DCMAKE_CXX_CLANG_TIDY="$(which clang-tidy);--warnings-as-errors=*"
- name: Run
run: cmake --build build -j 2
Best Practice: Use CMake-Format
There is a CMake formatting tool now too, called cmake-format ! You should use it to
keep your CMake code from becoming messy and keeping it easy to merge conflicts.
Since you should always use pre-commit for formatting and style checking, here's the
.pre-commit-config.yaml :
# CMake formatting
- repo: https://github.com/cheshirekow/cmake-format-precommit
rev: v0.6.13
hooks:
- id: cmake-format
additional_dependencies: [pyyaml]
types: [file]
files: (.cmake|CMakeLists.txt)(.in)?$
And here's the GitHub Actions job:
jobs:
pre-commit:
name: Format
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
- uses: pre-commit/action@v2.0.0
CompilerDetection and Flag checking
try_compile / try_run can tell you if a flag or file works. However, first check:
CheckCXXCompilerFlag
CheckIncludeFileCXX
CheckStructHasMember
TestBigEndian
CheckTypeSize
Best Bad Practice: WriteCompilerDetectionHeader will write out C/C++
macros for your compiler for you!
This has been removed in CMake 3.20. Feel free to set the minimum required to below
3.20, or find another tool, generate once, then keep the generated copy.
03-compiler/CMakeLists.txt
cmake_minimum_required(VERSION 3.15)
project(CompilerExample LANGUAGES CXX)
include(WriteCompilerDetectionHeader)
write_compiler_detection_header(
FILE my_compiler_detection.h
PREFIX MyPrefix
COMPILERS
GNU Clang MSVC Intel
FEATURES
cxx_variadic_templates
cxx_nullptr
)
In [ ]: cmake -S 03-compiler -B 03-build
Best Practice: Use FindPython and the newest possible
CMake (3.18.2+ best)
FindPython is an exciting new way to discover Python.
venv/conda ready.
Multiple runs (using unique caching system).
Not very usable till 3.15, not very usable for PyPy until 3.18.2+ and PyPy 7.3.2 (about
a week old)
But possibly vendorable to 3.7+
Scikit-build and CMake wheels
Scikit-build is an adaptor for setuptools (not a true PEP 517 builder). Combined with
pyproject.toml and Pip 10, it can be really useful, though!
Still not quite as reliable as setuptools (distutils) in non-standard setups
Doesn't work well without CMake wheels (but you can bypass PEP 518 if CMake is
already installed)
A little rough around some corners
Development a bit stuck.
Further investigation:
If we have some spare time, I can show you through the CMake systems I've helped design:
(Dual CMake / setuptools)
(CUDA and Scikit-Build)
I highly recommend my course and book
on CMake. Everything is linked from my blog,
.
Also, is fantastic, if you already know what you are looking for, it is
some of the best out there. The "new in" directives seem to be finally added in the 3.20
documentation! No more scrolling though old versions!
github.com/pybind/pybind11
github.com/pybind11/scikit_build_example
github.com/cliutils/cli11
github.com/scikit-hep/boost-histogram
github.com/goofit/goofit
hsf-training.github.io/hsf-training-cmake-webpage
cliutils.gitlab.io/modern-cmake
iscinumpy.gitlab.io
CMake's documentation
In [ ]:

More Related Content

What's hot

Gitlab ci, cncf.sk
Gitlab ci, cncf.skGitlab ci, cncf.sk
Gitlab ci, cncf.sk
Juraj Hantak
 
Introduction to GNU Make Programming Language
Introduction to GNU Make Programming LanguageIntroduction to GNU Make Programming Language
Introduction to GNU Make Programming Language
Shih-Hsiang Lin
 
Introduction to Makefile
Introduction to MakefileIntroduction to Makefile
Introduction to Makefile
Zakaria El ktaoui
 
Conan a C/C++ Package Manager
Conan a C/C++ Package ManagerConan a C/C++ Package Manager
Conan a C/C++ Package Manager
Uilian Ries
 
Devops Porto - CI/CD at Gitlab
Devops Porto - CI/CD at GitlabDevops Porto - CI/CD at Gitlab
Devops Porto - CI/CD at Gitlab
Filipa Lacerda
 
Monitoring MySQL Replication lag with Prometheus & pt-heartbeat
Monitoring MySQL Replication lag with Prometheus & pt-heartbeatMonitoring MySQL Replication lag with Prometheus & pt-heartbeat
Monitoring MySQL Replication lag with Prometheus & pt-heartbeat
Julien Pivotto
 
Introducing GitLab (June 2018)
Introducing GitLab (June 2018)Introducing GitLab (June 2018)
Introducing GitLab (June 2018)
Noa Harel
 
Introduction to docker
Introduction to dockerIntroduction to docker
Introduction to docker
Frederik Mogensen
 
Git & GitLab
Git & GitLabGit & GitLab
Git & GitLab
Gaurav Wable
 
Gitops Hands On
Gitops Hands OnGitops Hands On
Gitops Hands On
Brice Fernandes
 
Version Control with Git for Beginners
Version Control with Git for BeginnersVersion Control with Git for Beginners
Version Control with Git for Beginners
bryanbibat
 
Release With Maven
Release With MavenRelease With Maven
Release With Maveneugenn
 
Play with FILE Structure - Yet Another Binary Exploit Technique
Play with FILE Structure - Yet Another Binary Exploit TechniquePlay with FILE Structure - Yet Another Binary Exploit Technique
Play with FILE Structure - Yet Another Binary Exploit Technique
Angel Boy
 
DevOps avec Ansible et Docker
DevOps avec Ansible et DockerDevOps avec Ansible et Docker
DevOps avec Ansible et Docker
Stephane Manciot
 
Introduction To Makefile
Introduction To MakefileIntroduction To Makefile
Introduction To Makefile
Waqqas Jabbar
 
Tracing MariaDB server with bpftrace - MariaDB Server Fest 2021
Tracing MariaDB server with bpftrace - MariaDB Server Fest 2021Tracing MariaDB server with bpftrace - MariaDB Server Fest 2021
Tracing MariaDB server with bpftrace - MariaDB Server Fest 2021
Valeriy Kravchuk
 
Docker Tutorial.pdf
Docker Tutorial.pdfDocker Tutorial.pdf
Docker Tutorial.pdf
MuhammadYusuf767705
 
Using GitLab CI
Using GitLab CIUsing GitLab CI
Using GitLab CI
ColCh
 
eBPF Workshop
eBPF WorkshopeBPF Workshop
eBPF Workshop
Michael Kehoe
 

What's hot (20)

Gitlab ci, cncf.sk
Gitlab ci, cncf.skGitlab ci, cncf.sk
Gitlab ci, cncf.sk
 
Introduction to GNU Make Programming Language
Introduction to GNU Make Programming LanguageIntroduction to GNU Make Programming Language
Introduction to GNU Make Programming Language
 
Introduction to Makefile
Introduction to MakefileIntroduction to Makefile
Introduction to Makefile
 
Conan a C/C++ Package Manager
Conan a C/C++ Package ManagerConan a C/C++ Package Manager
Conan a C/C++ Package Manager
 
Devops Porto - CI/CD at Gitlab
Devops Porto - CI/CD at GitlabDevops Porto - CI/CD at Gitlab
Devops Porto - CI/CD at Gitlab
 
Monitoring MySQL Replication lag with Prometheus & pt-heartbeat
Monitoring MySQL Replication lag with Prometheus & pt-heartbeatMonitoring MySQL Replication lag with Prometheus & pt-heartbeat
Monitoring MySQL Replication lag with Prometheus & pt-heartbeat
 
Introducing GitLab (June 2018)
Introducing GitLab (June 2018)Introducing GitLab (June 2018)
Introducing GitLab (June 2018)
 
Introduction to docker
Introduction to dockerIntroduction to docker
Introduction to docker
 
Introduction to Git and Github
Introduction to Git and GithubIntroduction to Git and Github
Introduction to Git and Github
 
Git & GitLab
Git & GitLabGit & GitLab
Git & GitLab
 
Gitops Hands On
Gitops Hands OnGitops Hands On
Gitops Hands On
 
Version Control with Git for Beginners
Version Control with Git for BeginnersVersion Control with Git for Beginners
Version Control with Git for Beginners
 
Release With Maven
Release With MavenRelease With Maven
Release With Maven
 
Play with FILE Structure - Yet Another Binary Exploit Technique
Play with FILE Structure - Yet Another Binary Exploit TechniquePlay with FILE Structure - Yet Another Binary Exploit Technique
Play with FILE Structure - Yet Another Binary Exploit Technique
 
DevOps avec Ansible et Docker
DevOps avec Ansible et DockerDevOps avec Ansible et Docker
DevOps avec Ansible et Docker
 
Introduction To Makefile
Introduction To MakefileIntroduction To Makefile
Introduction To Makefile
 
Tracing MariaDB server with bpftrace - MariaDB Server Fest 2021
Tracing MariaDB server with bpftrace - MariaDB Server Fest 2021Tracing MariaDB server with bpftrace - MariaDB Server Fest 2021
Tracing MariaDB server with bpftrace - MariaDB Server Fest 2021
 
Docker Tutorial.pdf
Docker Tutorial.pdfDocker Tutorial.pdf
Docker Tutorial.pdf
 
Using GitLab CI
Using GitLab CIUsing GitLab CI
Using GitLab CI
 
eBPF Workshop
eBPF WorkshopeBPF Workshop
eBPF Workshop
 

Similar to CMake best practices

cmake.pdf
cmake.pdfcmake.pdf
cmake.pdf
Thejeswara Reddy
 
C make tutorial
C make tutorialC make tutorial
C make tutorial
zeng724
 
short_intro_to_CMake_(inria_REVES_team)
short_intro_to_CMake_(inria_REVES_team)short_intro_to_CMake_(inria_REVES_team)
short_intro_to_CMake_(inria_REVES_team)
Jérôme Esnault
 
IIT-RTC 2017 Qt WebRTC Tutorial (Qt Janus Client)
IIT-RTC 2017 Qt WebRTC Tutorial (Qt Janus Client)IIT-RTC 2017 Qt WebRTC Tutorial (Qt Janus Client)
IIT-RTC 2017 Qt WebRTC Tutorial (Qt Janus Client)
Alexandre Gouaillard
 
CMake Tutorial
CMake TutorialCMake Tutorial
CMake Tutorial
Fu Haiping
 
Readme
ReadmeReadme
Readme
rec2006
 
Makefile
MakefileMakefile
Makefile
Ionela
 
CMake_Tutorial.pdf
CMake_Tutorial.pdfCMake_Tutorial.pdf
CMake_Tutorial.pdf
Thejeswara Reddy
 
HPC_MPI_CICD.pptx
HPC_MPI_CICD.pptxHPC_MPI_CICD.pptx
HPC_MPI_CICD.pptx
ObjectAutomation2
 
Simple build tool
Simple build toolSimple build tool
Simple build tool
Knoldus Inc.
 
Autotools, Design Patterns and more
Autotools, Design Patterns and moreAutotools, Design Patterns and more
Autotools, Design Patterns and more
Vicente Bolea
 
Basic Cmake for Qt Users
Basic Cmake for Qt UsersBasic Cmake for Qt Users
Basic Cmake for Qt Users
ICS
 
How Helm, The Package Manager For Kubernetes, Works
How Helm, The Package Manager For Kubernetes, WorksHow Helm, The Package Manager For Kubernetes, Works
How Helm, The Package Manager For Kubernetes, Works
Matthew Farina
 
HPC_MPI_CICID_OA.pptx
HPC_MPI_CICID_OA.pptxHPC_MPI_CICID_OA.pptx
HPC_MPI_CICID_OA.pptx
ObjectAutomation2
 
Helm Charts Security 101
Helm Charts Security 101Helm Charts Security 101
Helm Charts Security 101
Deep Datta
 
Custum GNU/Linux Kali distribution
Custum GNU/Linux Kali distribution Custum GNU/Linux Kali distribution
Custum GNU/Linux Kali distribution
Mohamed BENCHENOUF
 
kubernetes for beginners
kubernetes for beginnerskubernetes for beginners
kubernetes for beginners
Dominique Dumont
 

Similar to CMake best practices (20)

cmake.pdf
cmake.pdfcmake.pdf
cmake.pdf
 
C make tutorial
C make tutorialC make tutorial
C make tutorial
 
C make tutorial
C make tutorialC make tutorial
C make tutorial
 
short_intro_to_CMake_(inria_REVES_team)
short_intro_to_CMake_(inria_REVES_team)short_intro_to_CMake_(inria_REVES_team)
short_intro_to_CMake_(inria_REVES_team)
 
IIT-RTC 2017 Qt WebRTC Tutorial (Qt Janus Client)
IIT-RTC 2017 Qt WebRTC Tutorial (Qt Janus Client)IIT-RTC 2017 Qt WebRTC Tutorial (Qt Janus Client)
IIT-RTC 2017 Qt WebRTC Tutorial (Qt Janus Client)
 
CMake Tutorial
CMake TutorialCMake Tutorial
CMake Tutorial
 
Install guide
Install guideInstall guide
Install guide
 
Install guide
Install guideInstall guide
Install guide
 
Readme
ReadmeReadme
Readme
 
Makefile
MakefileMakefile
Makefile
 
CMake_Tutorial.pdf
CMake_Tutorial.pdfCMake_Tutorial.pdf
CMake_Tutorial.pdf
 
HPC_MPI_CICD.pptx
HPC_MPI_CICD.pptxHPC_MPI_CICD.pptx
HPC_MPI_CICD.pptx
 
Simple build tool
Simple build toolSimple build tool
Simple build tool
 
Autotools, Design Patterns and more
Autotools, Design Patterns and moreAutotools, Design Patterns and more
Autotools, Design Patterns and more
 
Basic Cmake for Qt Users
Basic Cmake for Qt UsersBasic Cmake for Qt Users
Basic Cmake for Qt Users
 
How Helm, The Package Manager For Kubernetes, Works
How Helm, The Package Manager For Kubernetes, WorksHow Helm, The Package Manager For Kubernetes, Works
How Helm, The Package Manager For Kubernetes, Works
 
HPC_MPI_CICID_OA.pptx
HPC_MPI_CICID_OA.pptxHPC_MPI_CICID_OA.pptx
HPC_MPI_CICID_OA.pptx
 
Helm Charts Security 101
Helm Charts Security 101Helm Charts Security 101
Helm Charts Security 101
 
Custum GNU/Linux Kali distribution
Custum GNU/Linux Kali distribution Custum GNU/Linux Kali distribution
Custum GNU/Linux Kali distribution
 
kubernetes for beginners
kubernetes for beginnerskubernetes for beginners
kubernetes for beginners
 

More from Henry Schreiner

Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024
Henry Schreiner
 
Software Quality Assurance Tooling - Wintersession 2024
Software Quality Assurance Tooling - Wintersession 2024Software Quality Assurance Tooling - Wintersession 2024
Software Quality Assurance Tooling - Wintersession 2024
Henry Schreiner
 
Princeton RSE Peer network first meeting
Princeton RSE Peer network first meetingPrinceton RSE Peer network first meeting
Princeton RSE Peer network first meeting
Henry Schreiner
 
Software Quality Assurance Tooling 2023
Software Quality Assurance Tooling 2023Software Quality Assurance Tooling 2023
Software Quality Assurance Tooling 2023
Henry Schreiner
 
Princeton Wintersession: Software Quality Assurance Tooling
Princeton Wintersession: Software Quality Assurance ToolingPrinceton Wintersession: Software Quality Assurance Tooling
Princeton Wintersession: Software Quality Assurance Tooling
Henry Schreiner
 
What's new in Python 3.11
What's new in Python 3.11What's new in Python 3.11
What's new in Python 3.11
Henry Schreiner
 
Everything you didn't know you needed
Everything you didn't know you neededEverything you didn't know you needed
Everything you didn't know you needed
Henry Schreiner
 
SciPy22 - Building binary extensions with pybind11, scikit build, and cibuild...
SciPy22 - Building binary extensions with pybind11, scikit build, and cibuild...SciPy22 - Building binary extensions with pybind11, scikit build, and cibuild...
SciPy22 - Building binary extensions with pybind11, scikit build, and cibuild...
Henry Schreiner
 
SciPy 2022 Scikit-HEP
SciPy 2022 Scikit-HEPSciPy 2022 Scikit-HEP
SciPy 2022 Scikit-HEP
Henry Schreiner
 
PyCon 2022 -Scikit-HEP Developer Pages: Guidelines for modern packaging
PyCon 2022 -Scikit-HEP Developer Pages: Guidelines for modern packagingPyCon 2022 -Scikit-HEP Developer Pages: Guidelines for modern packaging
PyCon 2022 -Scikit-HEP Developer Pages: Guidelines for modern packaging
Henry Schreiner
 
PyCon2022 - Building Python Extensions
PyCon2022 - Building Python ExtensionsPyCon2022 - Building Python Extensions
PyCon2022 - Building Python Extensions
Henry Schreiner
 
boost-histogram / Hist: PyHEP Topical meeting
boost-histogram / Hist: PyHEP Topical meetingboost-histogram / Hist: PyHEP Topical meeting
boost-histogram / Hist: PyHEP Topical meeting
Henry Schreiner
 
Digital RSE: automated code quality checks - RSE group meeting
Digital RSE: automated code quality checks - RSE group meetingDigital RSE: automated code quality checks - RSE group meeting
Digital RSE: automated code quality checks - RSE group meeting
Henry Schreiner
 
Pybind11 - SciPy 2021
Pybind11 - SciPy 2021Pybind11 - SciPy 2021
Pybind11 - SciPy 2021
Henry Schreiner
 
RDM 2020: Python, Numpy, and Pandas
RDM 2020: Python, Numpy, and PandasRDM 2020: Python, Numpy, and Pandas
RDM 2020: Python, Numpy, and Pandas
Henry Schreiner
 
HOW 2019: Machine Learning for the Primary Vertex Reconstruction
HOW 2019: Machine Learning for the Primary Vertex ReconstructionHOW 2019: Machine Learning for the Primary Vertex Reconstruction
HOW 2019: Machine Learning for the Primary Vertex Reconstruction
Henry Schreiner
 
HOW 2019: A complete reproducible ROOT environment in under 5 minutes
HOW 2019: A complete reproducible ROOT environment in under 5 minutesHOW 2019: A complete reproducible ROOT environment in under 5 minutes
HOW 2019: A complete reproducible ROOT environment in under 5 minutes
Henry Schreiner
 
ACAT 2019: A hybrid deep learning approach to vertexing
ACAT 2019: A hybrid deep learning approach to vertexingACAT 2019: A hybrid deep learning approach to vertexing
ACAT 2019: A hybrid deep learning approach to vertexing
Henry Schreiner
 
2019 CtD: A hybrid deep learning approach to vertexing
2019 CtD: A hybrid deep learning approach to vertexing2019 CtD: A hybrid deep learning approach to vertexing
2019 CtD: A hybrid deep learning approach to vertexing
Henry Schreiner
 
2019 IRIS-HEP AS workshop: Boost-histogram and hist
2019 IRIS-HEP AS workshop: Boost-histogram and hist2019 IRIS-HEP AS workshop: Boost-histogram and hist
2019 IRIS-HEP AS workshop: Boost-histogram and hist
Henry Schreiner
 

More from Henry Schreiner (20)

Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024Modern binary build systems - PyCon 2024
Modern binary build systems - PyCon 2024
 
Software Quality Assurance Tooling - Wintersession 2024
Software Quality Assurance Tooling - Wintersession 2024Software Quality Assurance Tooling - Wintersession 2024
Software Quality Assurance Tooling - Wintersession 2024
 
Princeton RSE Peer network first meeting
Princeton RSE Peer network first meetingPrinceton RSE Peer network first meeting
Princeton RSE Peer network first meeting
 
Software Quality Assurance Tooling 2023
Software Quality Assurance Tooling 2023Software Quality Assurance Tooling 2023
Software Quality Assurance Tooling 2023
 
Princeton Wintersession: Software Quality Assurance Tooling
Princeton Wintersession: Software Quality Assurance ToolingPrinceton Wintersession: Software Quality Assurance Tooling
Princeton Wintersession: Software Quality Assurance Tooling
 
What's new in Python 3.11
What's new in Python 3.11What's new in Python 3.11
What's new in Python 3.11
 
Everything you didn't know you needed
Everything you didn't know you neededEverything you didn't know you needed
Everything you didn't know you needed
 
SciPy22 - Building binary extensions with pybind11, scikit build, and cibuild...
SciPy22 - Building binary extensions with pybind11, scikit build, and cibuild...SciPy22 - Building binary extensions with pybind11, scikit build, and cibuild...
SciPy22 - Building binary extensions with pybind11, scikit build, and cibuild...
 
SciPy 2022 Scikit-HEP
SciPy 2022 Scikit-HEPSciPy 2022 Scikit-HEP
SciPy 2022 Scikit-HEP
 
PyCon 2022 -Scikit-HEP Developer Pages: Guidelines for modern packaging
PyCon 2022 -Scikit-HEP Developer Pages: Guidelines for modern packagingPyCon 2022 -Scikit-HEP Developer Pages: Guidelines for modern packaging
PyCon 2022 -Scikit-HEP Developer Pages: Guidelines for modern packaging
 
PyCon2022 - Building Python Extensions
PyCon2022 - Building Python ExtensionsPyCon2022 - Building Python Extensions
PyCon2022 - Building Python Extensions
 
boost-histogram / Hist: PyHEP Topical meeting
boost-histogram / Hist: PyHEP Topical meetingboost-histogram / Hist: PyHEP Topical meeting
boost-histogram / Hist: PyHEP Topical meeting
 
Digital RSE: automated code quality checks - RSE group meeting
Digital RSE: automated code quality checks - RSE group meetingDigital RSE: automated code quality checks - RSE group meeting
Digital RSE: automated code quality checks - RSE group meeting
 
Pybind11 - SciPy 2021
Pybind11 - SciPy 2021Pybind11 - SciPy 2021
Pybind11 - SciPy 2021
 
RDM 2020: Python, Numpy, and Pandas
RDM 2020: Python, Numpy, and PandasRDM 2020: Python, Numpy, and Pandas
RDM 2020: Python, Numpy, and Pandas
 
HOW 2019: Machine Learning for the Primary Vertex Reconstruction
HOW 2019: Machine Learning for the Primary Vertex ReconstructionHOW 2019: Machine Learning for the Primary Vertex Reconstruction
HOW 2019: Machine Learning for the Primary Vertex Reconstruction
 
HOW 2019: A complete reproducible ROOT environment in under 5 minutes
HOW 2019: A complete reproducible ROOT environment in under 5 minutesHOW 2019: A complete reproducible ROOT environment in under 5 minutes
HOW 2019: A complete reproducible ROOT environment in under 5 minutes
 
ACAT 2019: A hybrid deep learning approach to vertexing
ACAT 2019: A hybrid deep learning approach to vertexingACAT 2019: A hybrid deep learning approach to vertexing
ACAT 2019: A hybrid deep learning approach to vertexing
 
2019 CtD: A hybrid deep learning approach to vertexing
2019 CtD: A hybrid deep learning approach to vertexing2019 CtD: A hybrid deep learning approach to vertexing
2019 CtD: A hybrid deep learning approach to vertexing
 
2019 IRIS-HEP AS workshop: Boost-histogram and hist
2019 IRIS-HEP AS workshop: Boost-histogram and hist2019 IRIS-HEP AS workshop: Boost-histogram and hist
2019 IRIS-HEP AS workshop: Boost-histogram and hist
 

Recently uploaded

Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Mind IT Systems
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Jay Das
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 

Recently uploaded (20)

Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
Custom Healthcare Software for Managing Chronic Conditions and Remote Patient...
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 

CMake best practices

  • 1. CMake: Best Practices Henry Schreiner Software & Computing Roundtable 2021-2-2 Links: The book: My blog: The workshop: This talk: launch launch binder binder cliutils.gitlab.io/modern-cmake iscinumpy.gitlab.io hsf-training.github.io/hsf-training-cmake-webpage gitlab.com/CLIUtils/modern-cmake-interactive-talk
  • 2. Intro to CMake In [ ]: cmake --version
  • 3. What is CMake? Is it a build system?
  • 4. Build system example (Rake): # 01-rake/Rakefile task default: [:hello_world] do # hello_world.c puts 'All built' # ↓ end # hello_world # ↓ file hello_world: ['hello_world.c'] do |t| # default task sh "gcc #{t.prerequisites.join(' ')} -o #{t.name}" end
  • 6. Features: Understands when to build/rebuild Doesn't understand how to build Generic; can be used for anything Examples make : Classic, custom syntax rake : Ruby make ninja : Google's entry, not designed to be hand written
  • 7. Build system generator Understands the files you are building System independent You give relationships Can find libraries, etc CMake is two-stage; the configuration step runs CMake, the build step runs a build-system ( make , ninja , IDE, etc). Aside: Modern CMake can run the install step directly without invoking the build system agian.
  • 8. Build system generator example (CMake): # 01-rake/CMakeLists.txt cmake_minimum_required(VERSION 3.11) project(HelloWorld) add_executable(hello_world hello_world.c)
  • 9. In [ ]: cmake -S 01-rake -B 01-build cmake --build 01-build
  • 10. C/C++ Examples cmake : Cross-platform Make (also Fortran, CUDA, C#, Swift) scons : Software Carpentry Construction (Python) meson : Newer Python entry basel : Google's build system Other languages often have their own build system (Rust, Go, Python, ...) We will follow common convention and call these "build- systems" for short from now on
  • 11. Why CMake? It has become a standard Approximately all IDEs support it Many libraries have built-in support Integrates with almost everything
  • 12. Custom Buildsystems are going away for CMake (note: C++17 only too) Boost is starting to support CMake at a reasonable level along with BJam Standout: Google is dual supporting Bazel and CMake Qt 6 dropped QMake
  • 13. Custom Buildsystems are going away for CMake (note: C++17 only too) Boost is starting to support CMake at a reasonable level along with BJam Standout: Google is dual supporting Bazel and CMake Qt 6 dropped QMake Recent highlights Thrust just received a major CMake overhaul TBB / Intel PSTL nicely support CMake in recent years Pybind11's CMake support was ramped up in 2.6
  • 14. (More) Modern CMake CMake is a new language to learn (and is a bit odd) Classic CMake (CMake 2.8, from 2009) was ugly and had problems, but that's not Modern CMake!
  • 15. Modern CMake and ! CMake 3.0 in 2014: Modern CMake begins CMake 3.1-3.4 had important additions/fixes CMake 3.12 in mid 2018 completed the "More Modern CMake" phase Current CMake is 3.19 (2.20 in rc2 phase) Eras of CMake Classic CMake: Directory based Modern CMake: Target based More Modern CMake: Unified target behavior CURRENT: Powerful CLI More Modern CMake
  • 16. Best Practice: Minimum Version is important! CMake has a (AFAIK) unique version system. If a file start with this: Then CMake will set all policies (which cover all behavior changes) to their 3.0 settings. This in theory means it is extremely backward compatible; upgrading CMake will not break or change anything at all. In practice, all the behavior changes had very good reasons to change, so this will be much buggier and less useful than if you set it higher! cmake_minimum_required(VERSION 3.0)
  • 17. You can also do this: Then CMake < 3.4 will be an error CMake 3.4 -- 3.11 will set 3.4 policies (feature was introduced in 3.12, but syntax is valid) CMake 3.12 -- 3.14 will set current policies CMake 3.15+ will set 3.14 policies cmake_minimum_required(VERSION 3.4...3.14)
  • 18. Don't: set this low without a range - it will harm users. Setting < 3.9 will break IPO, for example. Often in a way that can't be fixed by superprojects. Do: set the highest minimum you can (build systems are hard/ugly enough as it is) Do: test with the lowest version version you support in at least one job. Don't: expect a CMake version significanly older than your compiler to work with it (expecially macOS/Windows, or CUDA).
  • 19. What minimum to choose - OS support: 3.4: The bare minimum. Never set less. 3.7: Debian old-stable. 3.10: Ubuntu 18.04. 3.11: CentOS 8 (use EPEL or AppSteams, though) 3.13: Debian stable. 3.16: Ubuntu 20.04. 3.18: pip 3.19: conda-forge/chocolaty/direct download, etc. First to support Apple Silicon. What minimum to choose - Features: 3.8: C++ meta features, CUDA, lots more 3.11: IMPORTED INTERFACE setting, faster, FetchContent, COMPILE_LANGUAGE in IDEs 3.12: C++20, cmake --build build -j N , SHELL: , FindPython 3.14/3.15: CLI, FindPython updates 3.16: Unity builds / precompiled headers, CUDA meta features 3.17/3.18: Lots more CUDA, metaprogramming
  • 20. Best Practice: Running CMake The classic method: The modern method is cleaner and more cross-platform-friendly: (CMake 3.14/3.15) supports -v (verbose), -j N (threads), -t target , and more mkdir build cd build cmake .. make cmake -S . -B build cmake --build build
  • 21. Example options: In [ ]: cmake --build 01-build -v
  • 22. PUBLIC PRIVATE INTERFACE PUBLIC Public Library Main Library Private Library Interface Library Target: mylibrary Target: myprogram Best Practice: Use Targets Excutables and libraries are targets
  • 23. Properties include: Header include directories Compile flags and definitions Link flags C++ standard and/or compiler features required Linked libraries Note that other things include properties, like files (such as LANGUAGE), directories, and global
  • 24. Tips for packaging Do: use targets. Don't: use common names for targets if you want to be used in subdirectory mode. Don't: write a FindPackage for your own package. Always provide a PackageConfig instead. Export your targets to create a PackageTargets.cmake file. You can write a PackageConfig.cmake.in ; you can recreate / reimport package there (generally use a shared X.cmake file instead of doing it twice). Don't: hardcode any system/compiler/config details into exported targets. Only from shared code in Config, or use Generator expressions. Never allow your package to be distributed without the config files!
  • 25. Using other projects 1. See if the project provides a <name>Config.cmake file. If it does, you are good to go! 2. If not, see if CMake for it built-in. If it does, you are good to go! 3. If not, see if the authors provide a Find<name>.cmake file. If they do, complain loudly that they don't follow CMake best practices. 4. Write your own Find<name>.cmake and include in in a helper directory. You'll need to build IMPORTED targets and all that. 5. You can also use FindPkgConfig to piggy back on classic pkg-config. provides a Find package
  • 26. Best Practice: Handling remote dependencies CMake can download your dependencies for you, and can integrate with files. It supports composable (sub-)projects: One project can include another Does not have namespaces, can cause target collisions! Build time data and project downloads: ExternalProject (classic) Configure time downloads FetchContent (new in 3.11+) You can also use submodules (one of my favorite methods, but use with care) You can also use Conan.io's CMake integration
  • 28. FetchContent 02-fetch/hello_fmt.cpp #include <fmt/format.h> int main() { fmt::print("The answer is {}n", 42); return 0; }
  • 29. 02-fetch/CMakeLists.txt cmake_minimum_required(VERSION 3.14) project(HelloWorld LANGUAGES CXX) include(FetchContent) FetchContent_Declare( fmt GIT_REPOSITORY https://github.com/fmtlib/fmt.git GIT_TAG 5.3.0) FetchContent_MakeAvailable(fmt) # Shortcut from CMake 3.14 add_executable(hello_world hello_fmt.cpp) target_link_libraries(hello_world PRIVATE fmt::fmt) target_compile_features(hello_world PRIVATE cxx_std_11)
  • 30. In [ ]: cmake -S 02-fetch -B 02-build cmake --build 02-build
  • 31. Conan.io's conan-cmake Conan.io has a nice CMake integration tool. It should support binaries too, since Conan.io supports them! You must have conan installed, though - I'm using conan from conda-forge. It works with old versions of CMake, as well. cmake_minimum_required(VERSION 3.14) project(HelloWorld LANGUAGES CXX)
  • 32. # Conan bootstrap if(NOT EXISTS "${CMAKE_BINARY_DIR}/conan.cmake") message( STATUS "Downloading conan.cmake from https://github.com/conan-io/cmake-conan") file(DOWNLOAD "https://github.com/conan-io/cmake-conan/raw/v0.16.1/conan.cmake" "${CMAKE_BINARY_DIR}/conan.cmake") endif() include("${CMAKE_BINARY_DIR}/conan.cmake") conan_check(REQUIRED) conan_cmake_run( REQUIRES fmt/6.1.2 BASIC_SETUP CMAKE_TARGETS BUILD missing)
  • 33. You can also make a conanfile.txt and manage all your dependencies there. add_executable(hello_world hello_fmt.cpp) target_link_libraries(hello_world PRIVATE CONAN_PKG::fmt) target_compile_features(hello_world PRIVATE cxx_std_11)
  • 34. In [ ]: cmake -S 02b-conan -B 02b-build -DCMAKE_BUILD_TYPE=Release cmake --build 02b-build
  • 35. Best Practice: Use IMPORTED targets for things you don't build Now (3.11+) can be built with standard CMake commands! Can now be global with IMPORTED_GLOBAL You'll need to set them back up in your Config file (place in one common location for both CMakeLists and Config). add_library(ExternLib IMPORTED INTERFACE) # Classic # Modern set_property( target_include_directories( TARGET ExternLib INTERFACE /my/inc ExternLib ) APPEND PROPERTY INTERFACE_INCLUDE_DIRECTORIES /my/inc )
  • 36. Best Practice: Use CUDA as a language Cuda is now a first-class language in CMake! (3.9+) Replaces FindCuda. project(MY_PROJECT LANGUAGES CUDA CXX) # Super project might need matching? (3.14 at least) # Or for optional CUDA support project(MY_PROJECT LANGUAGES CXX) include(CheckLanguage) check_language(CUDA) if(CMAKE_CUDA_COMPILER) enable_language(CUDA) endif()
  • 37. Much like you can set C++ standards, you can set CUDA standards too: if(NOT DEFINED CMAKE_CUDA_STANDARD) set(CMAKE_CUDA_STANDARD 11) # Probably should be cached! set(CMAKE_CUDA_STANDARD_REQUIRED ON) endif()
  • 38. Much like you can set C++ standards, you can set CUDA standards too: if(NOT DEFINED CMAKE_CUDA_STANDARD) set(CMAKE_CUDA_STANDARD 11) # Probably should be cached! set(CMAKE_CUDA_STANDARD_REQUIRED ON) endif() You can add files with .cu extensions and they compile with nvcc. (You can always set the LANGUAGE property on a file, too). Separable compilation is a property: set_target_properties(mylib PROPERTIES CUDA_SEPERABLE_COMPILATION ON)
  • 39. New for CUDA in CMake 3.18 and 3.17! A new CUDA_ARCHITECTURES property You can now use Clang as a CUDA compiler CUDA_RUNTIME_LIBRARY can be set to shared FindCUDAToolkit is finally available I rewrote the CUDA versions support in 3.20 to be more maintainable and more accurate.
  • 40. Best Practice: Check for Integrated Tools First CMake has a lot of great tools. When you need something, see if it is built-in first! Useful properties (with CMAKE_* variables, great from the command line_: INTERPROCEDURAL_OPTIMIZATION : Add IPO POSITION_INDEPENDENT_CODE : Add -fPIC <LANG>_COMPILER_LAUNCHER : Add ccache <LANG>_CLANG_TIDY <LANG>_CPPCHECK <LANG>_CPPLINT <LANG>_INCLUDE_WHAT_YOU_USE
  • 41. Useful modules: CheckIPOSupported : See if IPO is supported by your compiler CMakeDependentOption : Make one option depend on another CMakePrintHelpers : Handy debug printing FeatureSummary : Record or printout enabled features and found packages
  • 42. Using clang-tidy in GitHub Actions example .github/workflow/format.yml : on: pull_request: push: jobs: clang-tidy: runs-on: ubuntu-latest container: silkeh/clang:10 steps: - uses: actions/checkout@v2 - name: Configure run: cmake -S . -B build -DCMAKE_CXX_CLANG_TIDY="$(which clang-tidy);--warnings-as-errors=*" - name: Run run: cmake --build build -j 2
  • 43. Best Practice: Use CMake-Format There is a CMake formatting tool now too, called cmake-format ! You should use it to keep your CMake code from becoming messy and keeping it easy to merge conflicts. Since you should always use pre-commit for formatting and style checking, here's the .pre-commit-config.yaml : # CMake formatting - repo: https://github.com/cheshirekow/cmake-format-precommit rev: v0.6.13 hooks: - id: cmake-format additional_dependencies: [pyyaml] types: [file] files: (.cmake|CMakeLists.txt)(.in)?$
  • 44. And here's the GitHub Actions job: jobs: pre-commit: name: Format runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 - uses: pre-commit/action@v2.0.0
  • 45. CompilerDetection and Flag checking try_compile / try_run can tell you if a flag or file works. However, first check: CheckCXXCompilerFlag CheckIncludeFileCXX CheckStructHasMember TestBigEndian CheckTypeSize
  • 46. Best Bad Practice: WriteCompilerDetectionHeader will write out C/C++ macros for your compiler for you! This has been removed in CMake 3.20. Feel free to set the minimum required to below 3.20, or find another tool, generate once, then keep the generated copy.
  • 47. 03-compiler/CMakeLists.txt cmake_minimum_required(VERSION 3.15) project(CompilerExample LANGUAGES CXX) include(WriteCompilerDetectionHeader) write_compiler_detection_header( FILE my_compiler_detection.h PREFIX MyPrefix COMPILERS GNU Clang MSVC Intel FEATURES cxx_variadic_templates cxx_nullptr )
  • 48. In [ ]: cmake -S 03-compiler -B 03-build
  • 49. Best Practice: Use FindPython and the newest possible CMake (3.18.2+ best) FindPython is an exciting new way to discover Python. venv/conda ready. Multiple runs (using unique caching system). Not very usable till 3.15, not very usable for PyPy until 3.18.2+ and PyPy 7.3.2 (about a week old) But possibly vendorable to 3.7+
  • 50. Scikit-build and CMake wheels Scikit-build is an adaptor for setuptools (not a true PEP 517 builder). Combined with pyproject.toml and Pip 10, it can be really useful, though! Still not quite as reliable as setuptools (distutils) in non-standard setups Doesn't work well without CMake wheels (but you can bypass PEP 518 if CMake is already installed) A little rough around some corners Development a bit stuck.
  • 51. Further investigation: If we have some spare time, I can show you through the CMake systems I've helped design: (Dual CMake / setuptools) (CUDA and Scikit-Build) I highly recommend my course and book on CMake. Everything is linked from my blog, . Also, is fantastic, if you already know what you are looking for, it is some of the best out there. The "new in" directives seem to be finally added in the 3.20 documentation! No more scrolling though old versions! github.com/pybind/pybind11 github.com/pybind11/scikit_build_example github.com/cliutils/cli11 github.com/scikit-hep/boost-histogram github.com/goofit/goofit hsf-training.github.io/hsf-training-cmake-webpage cliutils.gitlab.io/modern-cmake iscinumpy.gitlab.io CMake's documentation In [ ]: