# Reject extra arguments to a function

**URL:** <https://discourse.cmake.org/t/reject-extra-arguments-to-a-function/3895>\
**Category:** Code\
**Created:** [August 9, 2021, 9:09pm UTC](https://discourse.cmake.org/t/reject-extra-arguments-to-a-function/3895 "2021-08-09T21:09:19Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Eric\_Malenfant](https://discourse.cmake.org/user_avatar/discourse.cmake.org/eric_malenfant/32/244_2.png) [@Eric\_Malenfant](https://discourse.cmake.org/u/Eric_Malenfant)\
**Post date:** [August 9, 2021, 9:09pm UTC](https://discourse.cmake.org/t/reject-extra-arguments-to-a-function/3895/1 "2021-08-09T21:09:19Z")

</div>

AFAIU, any `function` can be invoked with extra arguments. For example:

```auto
function(Takes2Args MyArg1, MyArg2)
  #do stuff
  ...
endfunction()

```

can be invoked like this without error:

```auto
TakesTwoArgs("one" "two" "three")

```

I’d like a way to make sure that this kind of invocation causes an error or warning.  
The best I could come up with right now is add a validation at the start of the function like this:

```auto
function(Takes2Args MyArg1, MyArg2)
    if(ARGN)
        message(FATAL_ERROR "Unknown argument(s) passed to function 'Takes2Args': ${ARGN}")
    endif()
   #do stuff
   ...
endfunction()

```

Since most (all?) of our functions do not expect extra arguments, I’m looking for a way to generalize that, but fails to find one. I tried with a macro, like:

```auto
macro(RejectExtraArgs)
    if(ARGN)
        message(FATAL_ERROR "Unknown argument(s)': ${ARGN}")
    endif()
endmacro()

```

used like this:

```auto
function(Takes2Args MyArg1, MyArg2)
   RejectExtraArgs()
   #do stuff
   ...
endfunction()

```

but this does not seem to work (presumably because the value of `ARGN` inside the macro has its own value instead of inheriting from the function’s).

Any idea of how a `function` could be easily marked as incompatible with extra arguments?

Thanks,  
Éric

---

<div class="post-metadata">

**Author:** ![ben.boeckel](https://discourse.cmake.org/letter_avatar_proxy/v4/letter/b/ea5d25/32.png) [@ben.boeckel](https://discourse.cmake.org/u/ben.boeckel)\
**Post date:** [August 9, 2021, 11:49pm UTC](https://discourse.cmake.org/t/reject-extra-arguments-to-a-function/3895/2 "2021-08-09T23:49:06Z")

</div>

Your approach works with functions, but not macros because macros expand the `ARG*` variables before executing the code rather than setting the variables and then executing the code. For macros, you’re probably better off doing some `ARGC` testing or the like.

The way [I’ve done this before](https://gitlab.kitware.com/vtk/vtk/blob/master/CMake/vtkModule.cmake#L542-551) is to use `cmake_parse_arguments` and bail if there’s anything unrecognized.
