How to check whether a target has been added or no

2020-06-02 16:53发布

问题:

Assume I have a cmake macro that adds target (library or executable) based on some conditions

macro (conditionally_add target_name target_src condition)
  if (condition)
    add_library (target_name target_src)
  endif ()
endmacro()

My question is, after calling this function

conditionally_add (mylib mysrc.cc ${some_condition})

How can I check whether the library has been added? More specifically, I'd like to do something below

if (my_lib_is_added)    # HOW TO DO THIS?
  # Do something.
endif ()

回答1:

Use the TARGET clause of the if command:

conditionally_add (mylib mysrc.cc ${some_condition})
if (TARGET mylib)
  # Do something when target found
endif()


回答2:

It seems, there is still no way to iterate over targets in the CMake, so you'd need to do it yourself.

You'll need to create a custom variant of add_executable() and add_library() functions, which would do something like

function(my_add_executable TARGET)
  list(APPEND MY_TARGETS ${TARGET})
  add_executable(${TARGET} ${ARGN}
endfunction()function(my_add_executable TARGET)


标签: cmake