add_executable
Defines a new executable build target named <executable_name>. Lists the source files that will be compiled and linked to produce the binary. The target name can later be referenced by target_link_libraries, target_include_directories, etc. add_library vs add_executable
An executable has a main() function, can be run directly, and is always the end of the dependency chain. A library has no main() function, cannot run on its own, and exists only to be linked against by other targets. PRIVATE vs PUBLIC only matters for libraries — executables are always PRIVATE. Choosing PRIVATE vs PUBLIC for Libraries
Ask yourself: do my header files expose this dependency to the outside world? If the dependency appears in your headers, anything linking against you will also need it — use PUBLIC. If the dependency only appears in your .cpp files, it stays hidden inside — use PRIVATE. |
target_include_directories
Specifies include directories for a given target, making headers in those directories available via . means the directories are only used when building this target, not propagated to dependents.Other scope options are (propagated to dependents) and (only propagated, not used by the target itself).CMake File Traversal
The root CMakeLists.txt is the entry point and orchestrates the entire build. include() pulls in .cmake files early to register libraries and settings before any targets are defined. add_subdirectory() tells CMake to go into a folder and process the CMakeLists.txt there before continuing. Leaf CMakeLists.txt files define targets with add_executable or add_library and have no further add_subdirectory() calls. CMAKE_CURRENT_SOURCE_DIR
A built-in CMake variable that always points to the directory containing the currently processed CMakeLists.txt. Use it to build paths to files relative to the current CMakeLists.txt location. /.. moves up one directory, making it useful for referencing files in a parent folder. |
target_link_libraries
Specifies which libraries an executable or library target should be linked against. means the libraries are only used when building this target, not propagated to dependents.Without this, the linker would not know where to find the implementations of external code your target depends on. PRIVATE / PUBLIC
Controls whether dependencies are propagated to targets that link against this one. Use PRIVATE when a dependency only appears in .cpp files (hidden inside the implementation), use PUBLIC when a dependency appears in header files (exposed to the outside world). Executables are always PRIVATE since nothing ever links against them. |
Cheatography
https://cheatography.com
C++ (cmake) Cheat Sheet (DRAFT) by blakecromar
A cheat sheet on making cmake files
This is a draft cheat sheet. It is a work in progress and is not finished yet.