Table of Contents

CMake Installation

install(TARGETS target DESTINATION bin) installs a target to the specified directory under CMAKE_INSTALL_PREFIX. The default prefix is /usr/local on Unix. Run cmake --install . to install after building.

Installing executables:

add_executable(myapp main.cpp)
install(TARGETS myapp DESTINATION bin)

This installs the executable to <prefix>/bin/myapp.

Installing libraries:

add_library(mylib source.cpp)
install(TARGETS mylib
  LIBRARY DESTINATION lib
  ARCHIVE DESTINATION lib
  RUNTIME DESTINATION bin)

Installing headers:

install(FILES include/mylib.h DESTINATION include)
install(DIRECTORY include/ DESTINATION include)

The first installs a single file; the second installs a directory recursively.

Setting the install prefix:

cmake -DCMAKE_INSTALL_PREFIX=/usr ..
cmake --install .

Or in CMakeLists.txt:

set(CMAKE_INSTALL_PREFIX /usr/local)

Common directory structure:

install(TARGETS myapp DESTINATION bin)
install(TARGETS mylib DESTINATION lib)
install(FILES include/mylib.h DESTINATION include)
install(FILES README.md DESTINATION share/doc/mylib)

Exporting targets for consumers:

install(TARGETS mylib EXPORT mylib-targets
  LIBRARY DESTINATION lib
  ARCHIVE DESTINATION lib)
 
install(EXPORT mylib-targets DESTINATION lib/cmake/mylib)

This generates CMake config files so other projects can find_package(mylib) and link to your installed library.

Installation rules are evaluated at install time, not configuration time. Use conditionals sparingly (they're evaluated at config time). Use cmake --install . --verbose to see what's being installed.

Packaging:

set(CPACK_PACKAGE_NAME "myapp")
set(CPACK_PACKAGE_VERSION "1.0.0")
include(CPack)

This enables cpack to generate platform-specific installers (.tar.gz, .deb, .rpm, .msi).

Install rules are typically at the end of your main CMakeLists.txt. Always use absolute paths or CMAKE_INSTALL_PREFIX variables.