【问题标题】:With CMake, how can I "install an alias" to a library?使用 CMake,我如何向库“安装别名”?
【发布时间】:2019-12-28 21:44:13
【问题描述】:

我将 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.

我应该怎么做?

【问题讨论】:

    标签: build cmake alias


    【解决方案1】:

    您可以在正在安装的主配置文件创建一个别名,而不是“安装”一个别名来导出给用户。

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

    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

    【讨论】:

    • 实际上,我的目标是完全避免自己编写配置文件,而是让它们生成......另见this CMake issue
    • 是的,我知道(从your comment 到相关问题)您支持自动生成的配置文件。不幸的是,当前的 CMake 无法按您的意愿工作。 referenced issue 和一些 other ones 只是对此的确认。你真的想通过在 Stack Overflow 上发帖来影响 CMake 开发人员吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    • 2014-03-18
    • 2012-06-11
    • 1970-01-01
    相关资源
    最近更新 更多