首页 > 解决方案 > cmake get find_package 查找包特定变量

问题描述

所以,我想创建一个 C 库,它可以通过find_packagecmake 中的功能轻松地在其他项目中使用。具体来说,我想要一个名为 foo 的项目,可以像这样访问:

find_package (foo-1.0 REQUIRED)

message ("!--   foo found version \"${FOO_VERSION}\"")
message ("!--   foo include path \"${FOO_INCLUDE_DIRS}\"")
message ("!--   foo libraries \"${FOO_LIBRARIES}\"")

然后,这些变量可以与其他 cmake 项目中的目标一起使用,例如:

add_executable (example example.c)
target_include_directories (example PRIVATE "${FOO_INCLUDE_DIRS}")
target_link_libraries (example PRIVATE "${FOO_LIBRARIES}")

我的问题是:

  1. 应该以何种方式安装静态或共享 c 库以供find_package(也就是需要什么目的地)找到。
  2. 我如何公开变量FOO_LIBRARIES,以便find_package函数在项目调用中公开它们find_package

标签: ccmake

解决方案


我想出了如何做到这一点。基本上,您必须拥有.cmake.in充当配置文件模板的文件和最终包的配置版本文件。find_package将查看 cmake 配置和版本文件的以下位置:

${CMAKE_INSTALL_PREFIX}/include/${LIBKOF_NAMED_VERSION}
${CMAKE_INSTALL_PREFIX}/lib/${LIBKOF_NAMED_VERSION}

包文件夹在哪里LIBKOF_NAMED_VERSION,比如foo-1.2

libkof是我的包的名称,您可以在下面看到这是如何完成的:

# This cmake is responsible for installing cmake config and other version
# files.

# This sets the package specific versioning
set(LIBKOF_MAJOR_VERSION 1)
set(LIBKOF_MINOR_VERSION 0)
set(LIBKOF_PATCH_VERSION 0)

# This allows easy creation of the directories within /usr/local or another install
# prefix
set(LIBKOF_NAMED_VERSION libkof-${LIBKOF_MAJOR_VERSION}.${LIBKOF_MINOR_VERSION})

# These statements will create the directories needed for installs
install(DIRECTORY DESTINATION ${CMAKE_INSTALL_PREFIX}/include/${LIBKOF_NAMED_VERSION})
install(DIRECTORY DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/${LIBKOF_NAMED_VERSION})

# This tracks the name of the in files used to generate the package cmake files
set(LIBKOF_CONFIG_FILE libkof-config.cmake.in)
set(LIBKOF_CONFIG_VERSION_FILE libkof-config-version.cmake.in)

# The configure_file statements will exchange the variables for the values in this cmake file.
configure_file(${LIBKOF_CONFIG_FILE} libkof-config.cmake @ONLY)
configure_file(${LIBKOF_CONFIG_VERSION_FILE} libkof-config-version.cmake @ONLY)

# Installs to the output locations so they can be found with find_package()
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/libkof-config-version.cmake DESTINATION include/${LIBKOF_NAMED_VERSION})
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/libkof-config.cmake DESTINATION lib/${LIBKOF_NAMED_VERSION})

推荐阅读