Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional Argument in cmake macro

Tags:

cmake

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?

like image 636
amit kumar Avatar asked Aug 28 '09 12:08

amit kumar


2 Answers

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)
like image 142
Stuart Berg Avatar answered Oct 21 '22 05:10

Stuart Berg


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.

like image 40
JesperE Avatar answered Oct 21 '22 05:10

JesperE