From 39bfc6e82b32b462e85884a97ce0e979e3f93a78 Mon Sep 17 00:00:00 2001 From: "Daniel J. Rollins" Date: Mon, 29 Jan 2018 22:56:43 +0000 Subject: [PATCH] Export Catch as a CMake package and 'linkable' target Create a namespaced Catch2::Catch target that is 'linkable' through `target_link_libraries()` and export it so it is findable through `find_package()`. `find_package()` will find versions with the same major number and with minor number >= requested. This makes catch a lot easier to use in CMake-based projects. Whether it is found using `find_package` or included in the client project as a subdirectory, the client can include the catch headers per-target with `target_include_directories(target PRIVATE Catch2::Catch). Example usage: cmake_minimum_required(VERSION 3.1) # include Catch2 as subdirectory or installed package # add_subdirectory(Catch2) find_package(Catch2 VERSION 2.1.0 REQUIRED) add_executable(tests tests/catch_main.cpp) target_link_libraries(tests PRIVATE Catch2::Catch) --- CMakeLists.txt | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 19472de6..3579f0af 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.0) +cmake_minimum_required(VERSION 3.1) # detect if Catch is being bundled, # disable testsuite in that case @@ -405,3 +405,37 @@ if(NOT WIN32 OR NOT CMAKE_HOST_SYSTEM_NAME MATCHES Windows) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/catch.pc DESTINATION ${PKGCONFIG_INSTALL_DIR}) endif() + +# add catch as a 'linkable' target +add_library(Catch INTERFACE) + +# depend on some obvious c++11 features so the dependency is transitively added dependants +target_compile_features(Catch INTERFACE cxx_auto_type cxx_constexpr cxx_noexcept) + +target_include_directories(Catch + INTERFACE + $ + $ + $) + +# provide a namespaced alias for clients to 'link' against if catch is included as a sub-project +add_library(Catch2::Catch ALIAS Catch) + +set(CATCH_CMAKE_CONFIG_DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/Catch2") + +# create and install an export set for catch target as Catch2::Catch +install(TARGETS Catch EXPORT Catch2Config DESTINATION ${CMAKE_INSTALL_LIBDIR}) + +install(EXPORT Catch2Config + NAMESPACE Catch2:: + DESTINATION ${CATCH_CMAKE_CONFIG_DESTINATION}) + +# install Catch2ConfigVersion.cmake file to handle versions in find_package +include(CMakePackageConfigHelpers) + +write_basic_package_version_file(Catch2ConfigVersion.cmake + COMPATIBILITY SameMajorVersion) + +install(FILES + "${CMAKE_BINARY_DIR}/Catch2ConfigVersion.cmake" + DESTINATION ${CATCH_CMAKE_CONFIG_DESTINATION})