Cpp Notes

1.introduction

CMake introduction

CMake-like build systems solve:

  • Avoiding hard-coded paths
  • Building a package on multiple computers
  • Supporting CI (Continuous Integration)
  • Supporting different OSs, including different Unix flavors
  • Supporting multiple compilers
  • Using an IDE occasionally or not at all
  • Describing the program’s structure logically, not via flags and commands
  • Integrating external libraries
  • Utilizing tools like Clang-Tidy
  • Using a debugger

Why CMake?

  • CMake is widely supported by IDEs, making it a common choice when using multiple projects or libraries.
  • Pre-installed libraries often have CMake scripts (find or config), making integration easier.

Building a project with CMake:

# Classic CMake Build Procedure:
~/package $ cmake -S . -B build
~/package $ cmake --build build

# Installing (choose one command):

## From the build directory:
~/package/build $ make install
~/package/build $ cmake --build . --target install
~/package/build $ cmake --install . # CMake 3.15+ only

## From the source directory:
~/package $ make -C build install
~/package $ cmake --build build --target install
~/package $ cmake --install build # CMake 3.15+ only

Source vs. Build Directory

  • It's recommended to use --build to avoid being locked into using make.
  • Building from the build directory is more common, and some tools (e.g., CTest <3.20) still require it.
  • Using cmake --build allows for options like:
    • -v for verbose builds (CMake 3.14+)
    • -j N for parallel builds (CMake 3.12+)
    • --target or -t (CMake 3.15+) to specify a target

CMake Options

  • Cached variables are stored in CMakeCache.txt in the build directory.
  • Use -D on the command line to preset or modify cached variable values.

Common options:

  • -DCMAKE_BUILD_TYPE=: Choose between Release, RelWithDebInfo, Debug.
  • -DCMAKE_INSTALL_PREFIX=: Set the install location (e.g., /usr/local, ~/.local).
  • -DBUILD_SHARED_LIBS=: Set ON or OFF for shared libraries.
  • -DBUILD_TESTING=: Enable tests (commonly used but not universal).

Debugging CMake files

  • cmake --build build --verbose # CMake 3.14+ enables verbose output (alternatively, use VERBOSE=1).
  • Use --trace to print every CMake line that runs.
    • --trace-source="filename" (CMake 3.7+) limits output to the file of interest, which is useful when debugging specific files like CMakeLists.txt.