CMake

What Does “Build” Mean?

“Building” a program means transforming your source code into a runnable application.

It typically includes a few main steps:

  1. Preprocessing (optional, for C/C++):
    • Handles things like #include, #define, etc.
  2. Compiling:
    • Converts individual .cpp files (human-readable code) into .o or .obj files (machine-readable object files).
  3. Linking:
    • Combines all object files and libraries into a single executable (like my_program.exe or ./my_program).
  4. (Optional) Installation:
    • Moves the final binaries, libraries, headers to specific system directories (/usr/local/bin, etc.).

What is CMake?

CMake is a build system generator. It helps you build your C++ (or C, etc.) code by generating native build files (like Makefiles, Ninja, or Visual Studio projects) from a higher-level configuration.

Think of it as a translator between your project and the actual build tool on your platform.

Why Use CMake?

Without CMake, you’d have to manually write platform-specific build scripts (like Makefile, build.bat, or Xcode project files). CMake simplifies that and makes your codebase portable.

So instead of:

  • Writing a separate build script for Linux, Windows, macOS…

You write one CMake configuration: CMakeLists.txt.

Basic CMake Project Structure

my_project/
├── CMakeLists.txt
└── main.cpp

Example: CMakeLists.txt

cmake_minimum_required(VERSION 3.10) 
# Minimum CMake version
project(MyProject) 
# Project name
add_executable(my_program main.cpp) 
# Create an executable from main.cpp

Then you’d build like this:

mkdir build
cd build
cmake ..
make

This:

  1. Configures your project
  2. Generates a Makefile (or Ninja/Xcode/etc)
  3. Builds it with make (or whatever tool you chose)

Bonus Features

CMake supports:

  • Linking libraries (target_link_libraries)
  • Compiler flags
  • Unit testing
  • Installing files
  • Platform-specific tweaks
  • External dependencies (via FetchContent or find_package)

Typical Workflow

mkdir build
cd build
cmake .. # generate build system
cmake --build . # build the project

Optional:

ctest # run tests
cmake --install . # install the built binaries

What Are Native Build Files?

Native build files are scripts or project files that a specific build tool understands and uses to compile your code.

Think of it like this:

Platform/ToolNative Build File Type
Unix/LinuxMakefile (used by make)
Windows.sln and .vcxproj (used by Visual Studio)
Cross-platformbuild.ninja (used by Ninja)
macOSXcode project files (.xcodeproj)

These are “native” to the tools you’re using. They describe:

  • What files to compile
  • Compiler flags
  • Include directories
  • Libraries to link
  • Where to put the outputs