Skip to content

Building C/C++ Projects with CMake

CMake is a meta-build system: project metadata in CMakeLists.txt describes targets, while CMake generates native build files (Makefiles, Ninja, Visual Studio solutions). Use out-of-source builds to keep the source tree clean.

CMakeLists.txt:

cmake_minimum_required(VERSION 3.16)
project(hello C)
add_executable(hello src/main.c)
target_compile_features(hello PRIVATE c_std_11)

Build steps:

Terminal window
mkdir -p build && cd build
cmake -DCMAKE_BUILD_TYPE=Debug ..
cmake --build .
  • CMAKE_BUILD_TYPE=Debug|Release controls optimization and debug info
  • -DCMAKE_C_FLAGS="-Wall -Wextra" to surface warnings
  1. Prefer Ninja as the underlying backend for fast parallel builds: cmake -G Ninja ...
  2. Use find_package to locate dependencies (e.g., find_package(PkgConfig REQUIRED) then use pkg_check_modules).
  3. Keep tests in a tests/ directory and use enable_testing() + add_test().

This topic is an important part of building a reliable Linux development workflow. Understanding it clearly will make later tasks easier, because it reduces guesswork and helps you recognize when a step is missing or misapplied.

  • Try the commands or configuration shown here in a safe test environment.
  • Compare how the concepts apply across different distributions or tools.
  • Keep a short note of what worked and what failed so you can diagnose future problems faster.
  • Revisit the related article in the series to deepen the connections between topics.
  • Skipping verification steps and assuming the system is configured correctly.
  • Copying commands without adapting paths, package names, or tool versions for your environment.
  • Treating this topic as an isolated tip rather than part of a larger workflow.