How do I export targets and write package configs in CMake?

In CMake, exporting targets and writing package configuration files allows you to make your library or executable easily usable by other CMake projects. Below, we explain how to do this effectively with examples.

Exporting Targets

To export a target, you use the install(EXPORT ...) command after defining your targets. This will create an export file that other projects can use to find your targets.

Writing Package Configuration Files

Package configuration files are created using the configure_file() command. You can set it up to configure variables that other projects will need, such as include directories and linked libraries.

Example

# CMakeLists.txt
cmake_minimum_required(VERSION 3.0)
project(MyLibrary)

add_library(MyLibrary my_library.cpp)

install(TARGETS MyLibrary
    EXPORT MyLibraryExports
    LIBRARY DESTINATION lib
    ARCHIVE DESTINATION lib
    RUNTIME DESTINATION bin
)

install(EXPORT MyLibraryExports
    FILE MyLibraryConfig.cmake
    NAMESPACE MyLibrary::
    DESTINATION lib/MyLibrary
)

# Create a configuration file for the package
include(CMakePackageConfigHelpers)

configure_package_config_file(
    "MyLibraryConfig.cmake.in"
    "${CMAKE_CURRENT_BINARY_DIR}/MyLibraryConfig.cmake"
    INSTALL_DESTINATION "lib/MyLibrary"
)

install(FILES
    "${CMAKE_CURRENT_BINARY_DIR}/MyLibraryConfig.cmake"
    "${CMAKE_CURRENT_BINARY_DIR}/MyLibraryConfigVersion.cmake"
    DESTINATION lib/MyLibrary
)
    

CMake Export Targets Package Configs Build Systems Cross-Platform