Your first CMakeLists.txt file
Overview
Teaching: 10 min
Exercises: 10 minQuestions
How little can I get away with in my CMakeLists?
Objectives
Know how to write a CMakeLists.txt file
Writing a CMakeLists
The following file is fine for the following examples:
/* simple.c or simple.cpp */
#include <stdio.h>
int main() {
printf("Hello, World!");
return 0;
}
This file can be compiled with C or C++.
Starting off
This is the simplest possible CMakeLists.txt
:
cmake_minimum_required(VERSION 3.14)
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 a
CXX
(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.
Those commands have a few extra arguments that you can give:
cmake_minimum_required(VERSION 3.14...3.18)
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/henryiii/cmake_workshop.git
cd cmake_workshop/code/00-intro
Solution
More reading
- Based on Modern CMake basics
Key Points
Write CMakeLists.txt files