Return a list from the function using OUT parameter
Here's how I solved a similar problem which was marked a duplicate of this question. This function takes a string BinaryName
and adds it to the list OutVariable
which is available in the parent scope. If the list is not defined it is created. I use this strategy for creating new test targets and adding the name of these targets to a list of targets in the main scope.
Thanks to @Tsyvarev
for the comments that lead me to figure this out.
function(AddToListFromFunction BinaryName OutVariable)
if ("${${OutVariable}}" STREQUAL "")
message(STATUS "1")
set(${OutVariable} ${BinaryName} PARENT_SCOPE)
message(STATUS "OutVariable: ${OutVariable} ${${OutVariable}}")
else ()
message(STATUS "2")
set(${OutVariable} "${${OutVariable}}" "${BinaryName}" PARENT_SCOPE)
endif ()
endfunction()
AddToListFromFunction(MyBinary1 MyTests)
AddToListFromFunction(MyBinary2 MyTests)
message(STATUS "MyTests Variable: ${MyTests}")
Check that inside your function you are set()
ing not dst_list
but ${dst_list}
. You need this to return data to the parent scope.
In CMake, functions have their own scope, and by default, all modification of variables are local, unless you pass CACHE
or PARENT_SCOPE
as parameter to set
. Inside a function, if you want to modify a variable in the scope of the caller, you should use:
set(${dst_list} <something> PARENT_SCOPE)
See documentation:
A function opens a new scope: see set(var PARENT_SCOPE) for details.