Your first CMakeLists.txt file
Overview
Teaching: 10 min
Exercises: 10 minQuestions
How little can I get away with in my CMakeLists?
Objectives
Understand the deep implications of
cmake_minimum_version
Know how to set up a project
Know how to make at least one target
Writing a CMakeLists
The following file is fine for the following examples:
This file can be compiled with C or C++.
Starting off
This is the simplest possible CMakeLists.txt
:
cmake_minimum_required(VERSION 3.15)
project(MyProject)
add_executable(myexample simple.cpp)
Let’s look at the three lines:
- The
cmake_minimum_required
command sets the policies so that the build is exactly like it would be on the listed version of CMake - in other words, CMake “dumbs itself down” to the version you request for any features that could produce a different build. This makes CMake almost perfectly backwards compatible. - You need to be working on a
project
, and it needs at least a name. CMake assumes aCXX
(that’s C++) andC
mixed project if you don’t give anyLANGUAGES
. - You need at least one library or executable to do anything interesting. The “thing” you make here
is called a “target”, and the executable/library has the same name, by default, and it has to be
unique in the project. You use
add_executable
for programs, andadd_library
for libraries.
Those commands have a few extra arguments that you can give:
cmake_minimum_required(VERSION 3.15...3.25)
project(MyProject
VERSION
1.0
DESCRIPTION
"Very nice project"
LANGUAGES
CXX
)
add_executable(myexample simple.cpp)
- You can specify a range of versions - this will cause the policies to be set to the highest supported value in that range. As a general rule, set the highest version you’ve tested with here.
- Projects can have versions, descriptions, and languages.
- Whitespace doesn’t matter. Be clear/pretty, or use cmake-format.
Try it out
Build and run the example code with a CMakeLists.txt
similar to the one above.
git clone https://github.com/hsf-training/hsf-training-cmake-webpage.git
cd hsf-training-cmake-webpage/code/00-intro
More reading
- Based on Modern CMake basics
Key Points
The
cmake_minimum_version
setting has deep implicationsYou need a project line.
You should prepare one or more targets to do anything interesting.