Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CMake: Howto modify a variable from inside a function

Tags:

function

cmake

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:

  • Modify a variable inside a function is about JavaScript not CMake

  • Is JavaScript a pass-by-reference or pass-by-value language? is about JavaScript not CMake

like image 245
Frank-Rene Schäfer Avatar asked Jul 18 '26 20:07

Frank-Rene Schäfer


1 Answers

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()
like image 64
KamilCuk Avatar answered Jul 20 '26 18:07

KamilCuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!