[CMake] Defining a function in a macro

Walter Gray chrysalisx at gmail.com
Fri Aug 1 20:30:43 EDT 2014


Hey List -
Just wanted to put this out there for posterity, and in case anyone runs 
into the same question I had.  I had a bunch of nearly identical 
functions, so I wanted to write a function to define them for me to 
reduce code repetition.  The problem I ran into was that if you write

macro(_define_function name)
   function(namespaced_${function_name} ...)
       message(${ARGV} from ${name})
   endfunction()
endmacro()

_define_function(foo)
namespaced_foo("Message")

you actually wind up printing "foo from foo", since all variable 
references to a macro are expanded first.  I also couldn't use a 
function, since there would be no way to access ${name} from inside the 
function (that I'm aware of - please correct me on this if I'm wrong)

The solution I came up with was, if I wanted to reference the function's 
argv, I would do a double-dereference of a string containing "ARGV" like so:

macro(_define_function name)
   function(namespaced_${function_name} ...)
       set(my_argv ARGV)
       message(${${my_argv}} from ${name})
   endfunction()
endmacro()

This produced the correct results.  If any of you know of a cleaner way 
to do this, I'd love to hear about it.  If not, have fun writing 
functions to write your functions!

As a relatively useless, but I thought entertaining aside:

macro(_define_function name my_argv)
   function(namespaced_${function_name} ...)
       message(${my_argv} from ${name})
   endfunction()
endmacro()
_define_function(foo "\${ARGV}")
namespaced_foo("Message")

The result is "foo Message from foo" because ${my_argv} gets expand to 
${ARGV}, which then expands to "foo ${ARGV}".

Thanks!


More information about the CMake mailing list