Important Variables
CMAKE_CURRENT_SOURCE_DIR
Directory containing the current CMakeLists.txt.
Example:
${CMAKE_CURRENT_SOURCE_DIR}/includeIf the project is
calcpack/
├── CMakeLists.txt
├── include/
└── src/then
${CMAKE_CURRENT_SOURCE_DIR}
/path/to/calcpackUnlike CMAKE_SOURCE_DIR, this changes when entering subdirectories with add_subdirectory().
GNUInstallDirs
include(GNUInstallDirs)Provides standard installation directories in a portable way.
| Variable | Typical Value | Purpose |
|---|---|---|
CMAKE_INSTALL_BINDIR | bin | Executables |
CMAKE_INSTALL_INCLUDEDIR | include | Header files |
CMAKE_INSTALL_LIBDIR | lib (sometimes lib64) | Libraries |
Example:
install(
TARGETS calcapp
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)becomes
install/
└── bin/
└── calcappWhy use these variables?
Instead of
DESTINATION libuse
DESTINATION ${CMAKE_INSTALL_LIBDIR}Benefits:
- Portable across Linux, macOS, and Windows
- Supports distributions using
lib64or custom library paths - Modern CMake best practice
Library Target
add_library(calcpack src/calc.cpp)Creates a target named:
calcpackLink it with:
target_link_libraries(app PRIVATE calcpack)Target Alias
add_library(calcpack::calcpack ALIAS calcpack)Creates a second name for the same target.
Both are equivalent:
target_link_libraries(app PRIVATE calcpack)target_link_libraries(app PRIVATE calcpack::calcpack)The :: is a convention indicating a namespaced CMake target.
Examples:
fmt::fmt
Qt6::Core
Boost::filesystem
OpenSSL::SSL
calcpack::calcpackBenefits:
- Clearer code
- Matches imported libraries from
find_package() - Consistent names before and after installation
Key Takeaways
CMAKE_CURRENT_SOURCE_DIR→ current source directory.CMAKE_INSTALL_*DIR→ standard installation locations.GNUInstallDirsworks on Linux, macOS, and Windows.add_library(... ALIAS ...)creates another name for the same target.- Prefer namespaced targets (
project::library) in modern CMake.