How to write a nice function that passes variables

2019-02-04 06:17发布

问题:

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!

回答1:

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"



回答2:

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


标签: cmake