I have not enough reputation to comment on Sakra answer...
One problem I see with that solution is that if you use any subdirectory the changes you do to the variable _allTargets inside the subdirectory will not be propagated to the parent scope.
Digging more, list(append ...) cannot be used in this case:
Similar to the SET command, the LIST command creates new variable
values in the current scope, even if the list itself is actually
defined in a parent scope. To propagate the results of these
operations upwards, use SET with PARENT_SCOPE, SET with CACHE
INTERNAL, or some other means of value propagation.
http://www.cmake.org/cmake/help/v2.8.11/cmake.html#command:set :
If PARENT_SCOPE is present, the variable will be set in the scope
above the current scope. Each new directory or function creates a
new scope. This command will set the value of a variable into the
parent directory or calling function (whichever is applicable to the
case at hand).
(note for myself: a macro is not a function)
I don't see a general solution (e.g. independent from using add_subdirectory) when using PARENT_SCOPE. However, here there seem to be a solution using CACHE INTERNAL.
Quoting from: http://www.cmake.org/pipermail/cmake/2007-November/018109.html
# A macro for passing lists between different directories
# through an internal cache variable.
MACRO (APPEND_INTERNAL_LIST LIST_NAME VALUE)
# If the list in not in the cache, create it.
IF (${LIST_NAME})
SET (${LIST_NAME} "${${LIST_NAME}};${VALUE}" CACHE INTERNAL "Internal
variable")
ELSE (${LIST_NAME})
SET (${LIST_NAME} "${VALUE}" CACHE INTERNAL "Internal variable")
ENDIF (${LIST_NAME})
ENDMACRO (APPEND_INTERNAL_LIST)
# A macro for passing lists between different directories
# through an internal cache variable.
# This function empties the variable (usually because of older runs)
MACRO (INITIALIZE_INTERNAL_LIST LIST_NAME)
SET (${LIST_NAME} "" CACHE INTERNAL "Internal variable")
ENDMACRO (INITIALIZE_INTERNAL_LIST)