Intermediate level · Module 5: Builds and Debugging with CMake and GDB · Lesson 1 of 3
Multi-File Projects and CMake
Organise code into headers and sources, and describe the build with CMake so it works on any machine.
In this lesson you will
- Write a CMakeLists.txt for an executable with several source files
- Run out-of-source builds in debug and release modes
Key concepts
CMakeLists.txtadd_executableout-of-source buildCMAKE_BUILD_TYPE
The lesson
As projects grow, compiling with long g++ commands becomes error-prone. CMake describes the project once in CMakeLists.txt and generates build files for Make, Ninja or Visual Studio.
A minimal file sets the minimum version, the project name, the C++ standard and the executable: add_executable(pharmacy src/main.cpp src/stock.cpp). Warnings are added with target_compile_options.
Build outside the source tree: cmake -S . -B build, then cmake --build build. Debug builds include symbols for debugging; release builds are optimised. Never commit the build folder.
Step by step
- Create CMakeLists.txt for the pharmacy project.
- Configure and build in a build folder.
- Add warning flags with target_compile_options.
- Build once in Debug and once in Release.
Practice activity
Convert your Beginner level project to CMake and build it from a clean folder.
Expected result: The project builds with two CMake commands from a fresh clone.
Check your understanding
-
What does an out-of-source build mean?
Show answer
Build files go into a separate folder, keeping the source tree clean.
-
Which command adds an executable target?
Show answer
add_executable.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.