Exporting Targets
Installing a library's files is half the job. The other half is telling other CMake projects how to use them: which file is the library, which include directory, which compile features, which dependencies. CMake writes that description for you as an export file: a generated .cmake script that recreates your targets as imported targets on the consumer's side.
There are two kinds:
| Command | Writes | Points at | Used for |
|---|---|---|---|
install(EXPORT …) |
<prefix>/lib/cmake/<Pkg>/<Pkg>Targets.cmake at install time |
the installed files | packages, SDKs, system installs |
export(EXPORT …) |
<build>/<Pkg>Targets.cmake at configure time |
the build tree | using a library straight from another project's build directory, without installing |
Step 1: add targets to an export set
install(TARGETS … EXPORT <set>) installs the files and records the targets in a named export set:
cmake
install(TARGETS greet EXPORT GreetTargets)Step 2: write the export set out
cmake
install(EXPORT GreetTargets
NAMESPACE Greet:: # consumers see Greet::greet
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/Greet)The whole thing, and what it generates
bash · try it yourself
mkdir -p greet/include/greet greet/src && cd greet
cat > include/greet/greet.hpp <<'SRC'
#pragma once
#include <string>
namespace greet { std::string hello(const std::string& who); }
SRC
cat > src/greet.cpp <<'SRC'
#include <greet/greet.hpp>
std::string greet::hello(const std::string& who) { return "Hello, " + who + "!"; }
SRC
cat > CMakeLists.txt <<'CM'
cmake_minimum_required(VERSION 3.25)
project(Greet VERSION 1.4.0 LANGUAGES CXX)
include(GNUInstallDirs)
add_library(greet src/greet.cpp)
add_library(Greet::greet ALIAS greet)
target_include_directories(greet PUBLIC
lt;BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
lt;INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>)
target_compile_features(greet PUBLIC cxx_std_17)
install(TARGETS greet EXPORT GreetTargets)
install(DIRECTORY include/ DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
install(EXPORT GreetTargets NAMESPACE Greet::
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/Greet)
export(EXPORT GreetTargets NAMESPACE Greet::
FILE ${CMAKE_CURRENT_BINARY_DIR}/GreetTargets.cmake)
CM
cmake -S . -B build -G Ninja --log-level=NOTICE -DCMAKE_BUILD_TYPE=Release > /dev/null
cmake --build build > /dev/null
cmake --install build --prefix "$HOME/sdk" | grep cmake/Greet
echo "--- the interesting part of GreetTargets.cmake"
grep -v '^#' ~/sdk/lib/cmake/Greet/GreetTargets.cmake | sed -n '/^add_library/,/^)/p'
echo "--- GreetTargets-release.cmake"
grep -v -e '^#' -e '^