I want to create a macro whose argument is optional. If not specified, the argument's value should be an empty string. How can I do this?
Any arguments named in your macro definition are required for callers. However, your macro can still accept optional arguments as long as they aren't explicitly named in the macro definition.
That is, callers are permitted to pass in extra arguments (which were not named in the macro's argument list). Your macro can check for the existence of such extra arguments by checking the ${ARGN}
variable.
Beware: ARGN
is not a "normal" cmake variable. To use it with the list()
command, you'll need to copy it into a normal variable first:
macro (mymacro required_arg1 required_arg2)
# Cannot use ARGN directly with list() command,
# so copy it to a variable first.
set (extra_args ${ARGN})
# Did we get any optional args?
list(LENGTH extra_args extra_count)
if (${extra_count} GREATER 0)
list(GET extra_args 0 optional_arg)
message ("Got an optional arg: ${optional_arg}")
endif ()
endmacro (mymacro)
CMake does not (AFAIK) check the number of variables passed to a macro, so you can just go ahead and declare it as any other macro.
There is also a variable ${ARGN}
which expands to a list of all the "remaining" variables passed to a macro, which may be useful.
Update As stated in Sam's comment, CMake now fails unless all expected (named) arguments are given when calling a macro or function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With