Lesson 3 · Foundations

Your first CMake project

Hello World with CMake. A two-file project, the minimal CMakeLists.txt, and the two commands that build it.

Time for your first real project. It is tiny, but it contains every idea you will reuse from now on. Here is the whole thing:

hello/
├── CMakeLists.txt
└── src/
    └── main.cpp

Why

Every CMake project, even one with 10,000 files, is built from the same pieces. A CMakeLists.txt that describes the project, and a source directory. Learn this shape once and you have learned them all.

The code

src/main.cpp
#include <iostream> int main() { std::cout << "Hello from CMake!\n"; return 0; }

A completely normal C++ program. Now the file that tells CMake what to build:

CMakeLists.txt
# The minimum CMake version this project needs. # The version number and the "..." syntax are explained in lesson 6. cmake_minimum_required(VERSION 4.4) # Give the project a name and say which languages we use. project(hello LANGUAGES CXX) # Create an executable named "hello" from this source file. # The target name is also the name of the compiled program. add_executable(hello src/main.cpp)

That is it. Three commands. Here is what each one does:

CommandWhat it does
cmake_minimum_required(VERSION 4.4)Refuses to run with older CMake, and sets the policy behavior (lesson 6).
project(hello LANGUAGES CXX)Names the project and tells CMake we use C++.
add_executable(hello src/main.cpp)Creates a target named hello that compiles main.cpp into an executable.

Note

hello is a “target”. From lesson 7 onward, almost everything we do will be attached to a target. Remember this word. It is the most important concept in CMake.

Build it

Open a terminal in the hello/ folder and run two commands:

cmake -S . -B build
cmake --build build

The first line configures the project. CMake reads CMakeLists.txt and generates build files in the build/ folder. The second line builds it. The generated build tool compiles main.cpp.

Then run your program:

./build/hello
Hello from CMake!

What you just did

CMakeLists.txt ── configure ──► build/      (generates the build files)
src/main.cpp   ── build ──────► build/hello (compiles the program)

Tip

The build/ folder is generated. Never edit it by hand, and do not commit it to git. Add it to your .gitignore (lesson 4 covers this).

Pitfall

Do not put build files inside your source folder. If you see files like CMakeCache.txt or Makefile sitting next to your main.cpp, you configured “in-source” by running cmake . instead of cmake -S . -B build. Always use a separate build folder.

Read the docs