Return a list from the function using OUT parameter

前端 未结 3 1421
星月不相逢
星月不相逢 2020-11-29 11:16

I would like to create a CMake function as:

function(test src_list dst_list)
# do something
endfunction()

usage:

test(${my_lis         


        
相关标签:
3条回答
  • 2020-11-29 11:37

    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.

    0 讨论(0)
  • 2020-11-29 11:49

    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.

    0 讨论(0)
  • 2020-11-29 11:49

    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}")
    
    0 讨论(0)
提交回复
热议问题