I’m looking to provide sample code to a library built using CMake. The sample is hosted alongside the sources of the library in a folder called <project_root>/example
and I would like it to show how downstreams would use the library that are not part of the build. It doubles as test code for deployment tests in CI. The example has its own CMakeLists.txt
which is authored as a top-level CMake sciprt with project()
and everything, something like this:
cmake_minimum_required(VERSION
3.8 # CXX_STANDARD 17
)
project(example1
LANGUAGES CXX
)
find_package(hpc
REQUIRED
)
add_executable(${PROJECT_NAME}
example1.cpp
)
target_link_libraries(
PRIVATE
hpc::hpc
)
If I simply traverse this folder from the parent directory such as:
add_subdirectory(library)
if(BUILD_EXAMPLE)
add_subdirectory(example)
endif()
the find_package()
command is going to fail, even if the library already exists. I tried adding it to the build as an External Project like this:
if(${CMAKE_VERSION} VERSION_LESS "3.12.0")
string(REPLACE ";" "|" CMAKE_PREFIX_PATH_ALT_SEP "${CMAKE_PREFIX_PATH}")
else()
list(JOIN CMAKE_PREFIX_PATH "|" CMAKE_PREFIX_PATH_ALT_SEP)
endif()
ExternalProject_Add(example1
PREFIX ${PROJECT_BINARY_DIR}
SOURCE_DIR ${CMAKE_CURRENT_LIST_DIR}/example1
LIST_SEPARATOR |
CMAKE_ARGS
"-DCMAKE_CXX_FLAGS=${CMAKE_CXX_FLAGS}"
"-DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}"
"-DCMAKE_PREFIX_PATH=${PROJECT_BINARY_DIR}/library/CMakeFiles/Export|${CMAKE_PREFIX_PATH_ALT_SEP}"
TEST_EXCLUDE_FROM_MAIN ON
DEPENDS hpc
)
however the generated package config files refer to relative library locations which are invalid inside the build tree.
[build] The imported target "hpc::hpc" references the file
[build]
[build] "C:/Users/mnagy/Source/Repos/hpc/.vscode/build/library/CMakeFiles/Export/lib/hpc.lib"
Indeed, hpc.lib
is located in ${PROJECT_BINARY_DIR}/library/hpc.lib
TL;DR
What is the best way to incorporate top-level CMakeLists.txt files into a build that rely on Package Config files generated by the currently running build?