Using alias targets in CMake

2019-02-17 04:47发布

问题:

When defining CMake targets one can create alias targets so that the alias name can be used to refer to the defined target in subsequent commands. For instance

add_library(foo_lib foo.cpp bar.cpp bat.cpp)
add_library(foo::lib ALIAS foo_lib)

As far as I understood it, this has the advantage that the name foo_lib doens't appear as a make target. However, given such an alias name I'd like to set all kinds of properties to them such as:

set_target_properties(foo::lib PROPERTIES COMPILE_DEFINITIONS ...)
target_include_directories(foo::lib PUBLIC ... PRIVATE ...)

but this is not possible unfortunately, since CMake Error: set_target_properties can not be used on an ALIAS target. I don't see why this shouldn't be possible as I'd like to define the name of my lib once and refer to the given alias whenever I want to adjust a property of the target. Any hints on how to use ALIAS targets "correctly"? What is the purpose of ALIAS targets other than they're not appearing as Make targets then?

回答1:

ALIAS similar to "synonym". ALIAS target is just another name for original one. So the requirement for ALIAS target to be non-modifiable - you cannot adjust its properties, install it, etc.

One of possible scenario for creating alias - having target, which conceptionally differ from original one, but effectively the same (e.g., in given configuration):

if(FOO_USE_SHIPPED)
    add_library(FOO ...) # Library FOO shipped with our project
endif()

...

# We need FOO_test for testing
if(FOO_USE_SHIPPED)
    add_library(FOO_test ALIAS FOO) # Use our library
else()
    add_library(FOO_test IMPORTED)
    set_target_property(FOO_test ...) # Use external library
endif()


标签: c++ cmake