如何将CMake配置添加到构建树

3phpmpom  于 2022-11-11  发布在  其他
关注(0)|答案(1)|浏览(160)

我的项目中有一个带有cmake配置文件的共享库。我怎样才能使它在构建树中可用,这样我就不必在使用find_package之前安装它了?

yc0p9oo0

yc0p9oo01#

我所寻找的机制是export(PACKAGE <PackageName>)。请注意,从Python 3.15开始,默认情况下该命令不执行任何操作,因为填充用户包注册表会影响到源代码和构建树之外的内容。您必须设置CMAKE_EXPORT_PACKAGE_REGISTRY变量以将构建目录添加到CMake用户包注册表中。
我能让事情像这样运作:

install(
    TARGETS ${TARGET_LIB}
    EXPORT TARGET_LIB_EXPORTS  # Define exports
    FILE "${PROJECT_NAME}-targets.cmake"
    …
)

# Create targets file in build tree

export(
    EXPORT TARGET_LIB_EXPORTS
    FILE "${PROJECT_BINARY_DIR}/${PROJECT_NAME}-targets.cmake"
    NAMESPACE ${PROJECT_NAME}::
)

# Create config file in build tree

configure_package_config_file(
    "${PROJECT_SOURCE_DIR}/cmake/${PROJECT_NAME}-config.cmake.in"
    "${PROJECT_BINARY_DIR}/${PROJECT_NAME}-config.cmake"
    INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}-${PROJECT_VERSION}
)

# Create version config file in build tree

write_basic_package_version_file(
    "${PROJECT_NAME}-config-version.cmake"
    VERSION ${PROJECT_VERSION}
    COMPATIBILITY SameMajorVersion
)

# Export the package to make find_package work in build

set(CMAKE_EXPORT_PACKAGE_REGISTRY true)
export(PACKAGE ${PROJECT_NAME})

基本配置文件如下所示:

@PACKAGE_INIT@

include("${CMAKE_CURRENT_LIST_DIR}/@PROJECT_NAME@-targets.cmake")

相关问题