How to correctly create a CMake function with proper arguments

Problematic

In CMake, like in many other languages, it is possible to create and use functions.

Solutions

To make sure that your function has the right number of arguments when called, we have two solutions (two that I am aware of 😆).

Arguments count

This first solution consists of using a CMake variable available to us giving us the number of arguments used when the function is called.

function(my_function)
message("Number of parameters (including the function name)= \"${ARGC}\"")
message("List of parameters of the function = \"${ARGN}\"")
message("List of parameters of the function with the function name = \"${ARGV}\"")
if(NOT ${ARGC} EQUAL 3)
message(FATAL_ERROR "Call to 'my_function' with ${ARGC} arguments instead of 3")
endif()
endfunction()
my_function(param1, param2)

cmake_parse_arguments function

To face function with a big number of parameters and with different “kinds” of parameters, the CMake developers have created a new feature very interesting. Indeed, they have given us the ability to add keywords in our functions parameters so that we could group them by type, and check their validity more easily. Moreover, it even allow us to handle an infinity of parameters even more easily 😉

function(my_function)
set(options IS_ACTIVATED)
set(oneValueArgs NAME)
set(multiValueArgs ARRAY_OF_PARAM)
cmake_parse_arguments(MY_FUNCTION_REQUIRED
"${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
# If the name is not valid
if(MY_FUNCTION_NAME STREQUAL "Bad name")
message(FATAL_ERROR
"Error : The name passed as an argument is not valid.")
endif()
# If zero version are passed
if(NOT DEFINED MY_FUNCTION_ARRAY_OF_PARAM)
message(FATAL_ERROR "Missing ARRAY_OF_PARAM, please add one")
endif()
list(LENGTH MY_FUNCTION_ARRAY_OF_PARAM NUMBER_OF_PARAM_IN_ARRAY)
# If more than three params are passed
if(${NUMBER_OF_PARAM_IN_ARRAY} GREATER_EQUAL 3)
message( FATAL_ERROR
"Too much param (${NUMBER_OF_PARAM_IN_ARRAY}) given. Max : 3"
)
endif()
# Rest of the function
# ...
endfunction()

Interesting links

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store