[CMake] How to return a value from a macro

I’ll explain here, how one can return a value from a CMake macro.
I haven’t tested with other versions, but this is working with CMmake version 2.8.7.

Macro example

In the following example, one defines a macro named ‘test‘.
This macro accepts three arguments, which are, in this order, ‘placeholder‘, ‘valueOne‘ and ‘valueTwo‘.
The concatenation of the second and third arguments is set to the variable named ‘returnValue‘.

The trick

Now comes the trick:

  1. As its name implies the argument ‘placeholder‘ will act as a placeholder for the returned value, which is the value of the variable named ‘returnValue‘. This placeholder argument MUST be present and the first.
  2. When one call this macro ‘test‘, he MUST name its first parameter ‘returnValue‘.
  3. This ‘returnValue‘ variable MUST be initialized before the first call to the macro.

Code

macro( test placeholder valueOne valueTwo )
	set( returnValue"${valueOne} / ${valueTwo}" )
endmacro( test )

set( returnValue "start" )
message( "var: ${returnValue}" )

test( ${returnValue} "A" "B" )
message( "var: ${returnValue}" )

test( ${returnValue} "1" "2" )
message( "var: ${returnValue}" )

Results

Here is the result of the execution:

var: start
var: A / B
var: 1 / 2

Conclusion

Two actions:

  1. Add the placeholder argument, so the returned value can be retrieved outside of the macro.
  2. Name the variable which is carrying the returned value inside the macro like the variable which will take the value outside of the macro.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s