'Difference between "if(TARGET ..." and "if($<TARGET_EXISTS:..."
What is the difference between...
if(TARGET foo-bar)
...
and
if($<TARGET_EXISTS:foo-bar>)
...
My belief is that there is no difference. The value of the generator expression form is that it can be used in other contexts like within a custom_command... Yes?
Solution 1:[1]
The second version does not work.
There's no mention of generator expressions in the documentation of if and testing the syntax with both an existing and non-existing targets results in the condition being considered to be false. (Tested on windows with CMake version 3.22.1)
Furthermore if you think about it it does not make sense for generator expressions to work during the configuration: For multi-configuration generators you'd be missing the info about the configuration which could be part of the generator expression. The debugging suggestions for generator expressions also don't mention any way of using the value of a generator expression during the evaluation of the CMakeLists.txt files.
Difference in context allowing generator expressions
If you're using the generator expression in a context where it's allowed there is a difference: the generator expression is evaluated after cmake is done parsing, if(TARGET) just has access to the information available at the time cmake parses the command. If a target is generated after the logic, the generator expression will pick up on the existence of the target, if(TARGET) not.
if (TARGET MyTarget)
add_custom_target(Print COMMAND ${CMAKE_COMMAND} -E echo "exists")
else()
add_custom_target(Print COMMAND ${CMAKE_COMMAND} -E echo "doesn't exist")
endif()
add_custom_target(Print2 COMMAND ${CMAKE_COMMAND} -E echo "$<IF:$<TARGET_EXISTS:MyTarget>,exists,doesn't exist>")
add_executable(MyTarget ...)
The targetPrint prints doesn't exist,Print2 prints exists
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
