3

What is the best practice to modify a caller's variable from inside a CMake-function. Assume

function(MyFunction IN_OUT_NAME)

   ... what to do here ...

   string(APPEND ${IN_OUT_NAME} " and that")

   ... what to do here ...

endfunction()

What needs to be done such that the following code fragment

set(MY_MESSAGE "this")
MyFunction(MY_MESSAGE)
message(${MY_MESSAGE})

delivers

this and that

Not-a-duplicate-remarks:

2
  • set(variable ${varaible} PARENT_SCOPE) ? Commented Nov 13, 2018 at 10:16
  • Well, that sets it. But how can I read it? Commented Nov 13, 2018 at 10:16

1 Answer 1

6

Just use PARENT_SCOPE to export the value to parent scope:

function(MyFunction IN_OUT_NAME)
    string(APPEND ${IN_OUT_NAME} " and that")
    set(${IN_OUT_NAME} "${${IN_OUT_NAME}}" PARENT_SCOPE)
endfunction()
    
set(MY_MESSAGE "this")
MyFunction(MY_MESSAGE)
message(${MY_MESSAGE})

Alternate way, available since CMake 3.25 - use return(PROPAGATE ...):

function(MyFunction IN_OUT_NAME)
    string(APPEND ${IN_OUT_NAME} " and that")
    return(PROPAGATE ${IN_OUT_NAME})
endfunction()
Sign up to request clarification or add additional context in comments.

1 Comment

Important this ( Pre 3.25, have not tested the return() ) does not work when calling the function with an variable who's name is the same as the function parameter, in this case IN_OUT_NAME. set( IN_OUT_NAME "Test2" ) +MyFunction( IN_OUT_NAME ) won't modify the variable, this can come up in functions which use each other.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.