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
--buildto 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 --buildallows for options like:-vfor verbose builds (CMake 3.14+)-j Nfor parallel builds (CMake 3.12+)--targetor-t(CMake 3.15+) to specify a target
CMake Options
- Cached variables are stored in
CMakeCache.txtin the build directory. - Use
-Don the command line to preset or modify cached variable values.
Common options:
-DCMAKE_BUILD_TYPE=: Choose betweenRelease,RelWithDebInfo,Debug.-DCMAKE_INSTALL_PREFIX=: Set the install location (e.g.,/usr/local,~/.local).-DBUILD_SHARED_LIBS=: SetONorOFFfor 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, useVERBOSE=1).- Use
--traceto 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 likeCMakeLists.txt.