使用 CMake,我如何 "install an alias" 到图书馆?

With CMake, how can I "install an alias" to a library?

我将 CMake 用于库,目标名为 foo。但是 - 我还希望图书馆的用户能够将其称为 foo_altname。我试过这样做:

add_library(foo_alt ALIAS foo)
install(
  TARGETS foo foo_altname
  EXPORT strf)
# etc. etc.

...但这会触发错误! :

CMake Error at CMakeLists.txt:78 (install):
  install TARGETS given target "foo_altname" which is an alias.

我应该怎么做?

您可以在主配置文件创建别名,而不是"installing"导出给用户的别名] 正在安装。

记住:主要配置文件是您(作为项目的开发人员)编写的,安装后find_package会找到它。对不同的命令使用 EXPORT 选项,您只需要求 CMake 生成 附加 文件,这些文件将包含在主文件中。

fooConfig.cmake:

# Include the file generated by CMake. This would define IMPORTED target 'foo'.
include("${CMAKE_CURRENT_LIST_DIR}/fooTargets.cmake")

# Additional declarations for a user

# E.g. create an alias
add_library(foo_altname ALIAS foo)

CMakeLists.txt:

# ...
install(
  TARGETS foo
  EXPORT fooTargets)

# Assume all configuration files to be installed into lib/cmake/
install(
  EXPORT fooTargets
  DESTINATION "lib/cmake"

# Install a hand-written configuration file
install(
  FILES fooConfig.cmake
  DESTINATION "lib/cmake"

请注意,如果别名只是一个 前缀 目标的名称,那么您可以为 install(EXPORT) 命令使用 NAMESPACE 选项:

install(
  EXPORT fooTargets
  DESTINATION "lib/cmake"
  NAMESPACE alt::

这将提供 IMPORTED 目标 all::foo 而不是普通的 foo

有关创建配置文件的更多详细信息,请参阅 documentation