Tom de Geus
Tom de Geus

Reputation: 5985

Are targets appended?

I'm not entirely clear if calling, for instance, target_link_libraries() more than once for the same target will append the target's dependencies. For example, can I add options for the target main as follows?

option(ASSERT "Evaluate assertions" ON)

find_package(MyLib REQUIRED)

add_executable(main main.cpp)

target_link_libraries(main PRIVATE MyLib::MyLib)

if (ASSERT)
    target_link_libraries(main PRIVATE MyLib::enable_assert)
endif()

Upvotes: 0

Views: 50

Answers (1)

Kevin
Kevin

Reputation: 18396

Yes, from the target_link_libraries() documentation:

Repeated calls for the same <target> append items in the order called.

So in your example, this:

target_link_libraries(main PRIVATE MyLib::MyLib)
...
target_link_libraries(main PRIVATE MyLib::enable_assert)

is equivalent to this:

target_link_libraries(main PRIVATE MyLib::MyLib MyLib::enable_assert)

If you are using a simple boolean check to determine whether or not to include MyLib::enable_assert as an argument, you can use a conditional generator expression instead to simplify this logic:

target_link_libraries(main PRIVATE 
    MyLib::MyLib 
    $<IF:$<BOOL:${ASSERT}>, MyLib::enable_assert, > 
)

Upvotes: 3

Related Questions