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!

jww
  • 97,681
  • 90
  • 411
  • 885
nandaloo
  • 1,007
  • 2
  • 11
  • 16
  • https://github.com/boostcon/cppnow_presentations_2017/blob/master/05-19-2017_friday/effective_cmake__daniel_pfeifer__cppnow_05-19-2017.pdf suggests that you use macros when you want to modify a parameter. – James Moore Dec 06 '17 at 18:47
  • 2
    Your are correct, but it is not your fault. CMake is missing fundamental concepts of real scripting languages. – C.J. Apr 12 '19 at 17:23

2 Answers2

48

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"

Philipp
  • 11,549
  • 8
  • 66
  • 126
  • 2
    thanks a lot, it's working. However, I noticed some strange behaviour, see [here](http://stackoverflow.com/questions/14397298/cmake-strange-function-argument-name-behaviour) – nandaloo Jan 18 '13 at 10:49
8

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
Th. Thielemann
  • 2,592
  • 1
  • 23
  • 38