3

I have some target - say it's a library - in a CMakeLists.txt file of a repository I'm working on. I want to the following three to be separate:

  1. The target name I use in CMakeLists.txt; say it needs to be foo.
  2. The exported target name, which others will use after importing my installed repository: The prefix is mypackage, and I want the target name to be, say bar, so together it will be used as mypackage::bar by the importer.
  3. The library file basename; I want it to be libbaz, not libfoo nor libbar.

How can I achieve this?

I may be able to achieve two of these three using the ALIAS modifier of the add_library() command, but I want all three.

einpoklum
  • 118,144
  • 57
  • 340
  • 684
  • 1
    By assigning property [OUTPUT_NAME](https://cmake.org/cmake/help/latest/prop_tgt/OUTPUT_NAME.html) you could have any of the library file. However, *original* and *exported* target names could differ only by **prefix** (NAMESPACE parameter for [install(EXPORT)](https://cmake.org/cmake/help/latest/command/install.html#installing-exports)). Using `add_library(ALIAS)` you could **duplicate** original and/or exported targets with new names, but old names would still be accessible. – Tsyvarev Mar 03 '22 at 21:05
  • Another question about customizing **exported target name**: https://stackoverflow.com/questions/52704087/cmake-install-xxxtargets-cmake-with-a-different-name-from-the-original-target. – Tsyvarev Mar 03 '22 at 21:10
  • And the question about changing name of the library **file**: https://stackoverflow.com/questions/31038963/how-do-you-rename-a-library-filename-in-cmake. – Tsyvarev Mar 03 '22 at 21:12

1 Answers1

2

There are target properties that control this: OUTPUT_NAME and EXPORT_NAME. Here's how I would implement your scenario:

cmake_minimum_required(VERSION 3.22)
project(mypackage)

add_library(foo ...)
add_library(mypackage::bar ALIAS foo)

set_target_properties(
  foo
  PROPERTIES
  OUTPUT_NAME "baz"
  EXPORT_NAME "bar"
)

include(GNUInstallDirs)
set(mypackage_INSTALL_CMAKEDIR "${CMAKE_INSTALL_DATADIR}/cmake/mypackage"
    CACHE STRING "Installation destination for CMake files")

install(TARGETS foo EXPORT mypackage-targets)
install(
  EXPORT mypackage-targets
  DESTINATION "${mypackage_INSTALL_CMAKEDIR}"
  NAMESPACE mypackage::
)

# not shown: other install rules, components (incl. above), etc.

See the docs:

Alex Reinking
  • 16,724
  • 5
  • 52
  • 86