Important Variables

CMAKE_CURRENT_SOURCE_DIR

Directory containing the current CMakeLists.txt.

Example:

${CMAKE_CURRENT_SOURCE_DIR}/include

If the project is

calcpack/
├── CMakeLists.txt
├── include/
└── src/

then

${CMAKE_CURRENT_SOURCE_DIR}
/path/to/calcpack

Unlike CMAKE_SOURCE_DIR, this changes when entering subdirectories with add_subdirectory().


GNUInstallDirs

include(GNUInstallDirs)

Provides standard installation directories in a portable way.

VariableTypical ValuePurpose
CMAKE_INSTALL_BINDIRbinExecutables
CMAKE_INSTALL_INCLUDEDIRincludeHeader files
CMAKE_INSTALL_LIBDIRlib (sometimes lib64)Libraries

Example:

install(
    TARGETS calcapp
    RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
)

becomes

install/
└── bin/
    └── calcapp

Why use these variables?

Instead of

DESTINATION lib

use

DESTINATION ${CMAKE_INSTALL_LIBDIR}

Benefits:

  • Portable across Linux, macOS, and Windows
  • Supports distributions using lib64 or custom library paths
  • Modern CMake best practice

Library Target

add_library(calcpack src/calc.cpp)

Creates a target named:

calcpack

Link 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::calcpack

Benefits:

  • 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.
  • GNUInstallDirs works on Linux, macOS, and Windows.
  • add_library(... ALIAS ...) creates another name for the same target.
  • Prefer namespaced targets (project::library) in modern CMake.