CodeBlanks Logo Icon CodeBlanks

CMake basics

Learn build configuration with CMake.

What is CMake?

CMake is a build system generator for C++ projects. It does not compile directly; instead it produces Makefiles or Ninja files that build the project. It is cross-platform: the same build file works on Linux, macOS and Windows.

Every CMake project has a CMakeLists.txt at its root. The three basic commands are: cmake_minimum_required(VERSION 3.20) for the minimum version, project(MyApp) for the project name, and add_executable(myapp main.cpp) to define an executable target. After writing this file you run cmake . to generate build files.

project and add_executable

The project(MyApp) command names the project and sets the default language (C/C++). You can specify the language explicitly with project(MyApp LANGUAGES CXX). This command also defines the PROJECT_NAME variable.

The add_executable(myapp main.cpp) command defines an executable target named myapp. You can list source files one by one: add_executable(myapp main.cpp utils.cpp). The target name usually matches the project name. CMake compiles this target and produces the executable.

Practice Write your first CMakeLists.txt

Write a CMakeLists.txt. Define the version with cmake_minimum_required(VERSION 3.20), the project name with project(MyApp), and the executable target with add_executable(myapp main.cpp).

Starter code

main.cpp
# CMakeLists.txt
# Add the cmake commands here

Sample solution

main.cpp
cmake_minimum_required(VERSION 3.20)
project(MyApp)
add_executable(myapp main.cpp)

Expected output

Configuration ready

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does CMake produce?

  • An executable directly
  • C++ source code
  • Build files (Makefile or Ninja) Correct answer
  • A class diagram

Explanation: CMake produces Make or Ninja build files; they compile the project.

2 Complete the version command

Question
____(VERSION 3.20)
Answer
cmake_minimum_required(VERSION 3.20)

Explanation: cmake_minimum_required sets the minimum CMake version.

3 Match the command to its role

Term Meaning
cmake_minimum_required Minimum version
project(MyApp) Sets project name
add_executable Executable target
CMakeLists.txt Build file

All lessons in Advanced