26

as in said in the title, I would like to write a "nice" function in cmake that is able to modify a variable which is passed as a parameter into that function.

The only way I can think of doing it is ugly:

Function definition

function(twice varValue varName)
set(${varName} ${varValue}${varValue} PARENT_SCOPE)
endfunction(twice)

Usage

set(arg foo)
twice(${arg} arg)
message("arg = "${arg})

Result

arg = foofoo

It seems to me, there is no real concept of variables that one can pass around at all?! I feel like there is something fundamental about cmake that I didn't take in yet.

So, is there a nicer way to do this?

Thanks a lot!

2
  • github.com/boostcon/cppnow_presentations_2017/blob/master/… suggests that you use macros when you want to modify a parameter. Commented Dec 6, 2017 at 18:47
  • 2
    Your are correct, but it is not your fault. CMake is missing fundamental concepts of real scripting languages. Commented Apr 12, 2019 at 17:23

2 Answers 2

49

You don't need to pass the value and the name of the variable. The name is enough, because you can access the value by the name:

function(twice varName)
  SET(${varName} ${${varName}}${${varName}} PARENT_SCOPE)
endfunction()

SET(arg "foo")
twice(arg)
MESSAGE(STATUS ${arg})

outputs "foofoo"

Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot, it's working. However, I noticed some strange behaviour, see here
9

I use these two macros for debugging:

macro(debug msg)
    message(STATUS "DEBUG ${msg}")
endmacro()

macro(debugValue variableName)
    debug("${variableName}=\${${variableName}}")
endmacro()

Usage:

set(MyFoo "MyFoo's value")
debugValue(MyFoo)

Output:

MyFoo=MyFoo's value

Comments

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.