0

I want to define a few targets which have certain properties (say, dependencies and link libraries), and then go on to define other targets without those properties.

add_executable(foo src/foo1.cpp)
add_dependencies(foo some_dependency)
target_link_libraries(foo mylib)
add_executable(bar src/bar2.cpp)
add_dependencies(bar some_dependency)
target_link_libraries(bar mylib)
add_executable(baz src/baz3.cpp)
add_dependencies(baz some_dependency)
target_link_libraries(baz mylib)
# and now without the dependencies...
add_executable(quux src/qux.cpp)
add_executable(quuz src/quuz.cpp)

Is there a nice idiom for pushing and popping the relevant properties instead?

einpoklum
  • 118,144
  • 57
  • 340
  • 684

1 Answers1

1

I have struggled a lot with this myself. Unfortunately, I cannot say I have found a satisfying solution, partly because the CMake language is primitive and therefore quite limiting.

One idea that could be applied to the specific code sample would be to create a list of the relevant targets at some point after you've defined them and run a foreach loop using the commands that apply to all these in unison (i.e. in this case the add_dependencies and target_link_libraries). Extending on that, you can also use set_target_properties for setting multiple property-value pairs in one go.

add_executable(foo src/foo1.cpp)
add_executable(bar src/bar2.cpp)
add_executable(baz src/baz3.cpp)

set(SPECIAL_TRGTS foo bar baz)

foreach(trgt ${SPECIAL_TRGTS})
  add_dependencies(${trgt} some_dependency)
  target_link_libraries(${trgt} mylib)
endforeach()

# and/or

set_target_properties(${SPECIAL_TRGTS} PROPERTIES
  PROP1 val1
  PROP2 val2)

I guess it's also a matter of personal preference, and if the list of "special" targets is long enough to save LOCs when using the loop-based approach.

I'm also interested, if there's a clearly better approach on this matter.

compor
  • 2,239
  • 1
  • 19
  • 29