In CMake, functions are used to encapsulate a reusable block of code. Below is a detailed explanation of defining and calling functions in CMake.
Defining Functions
Function definitions start with function()
, followed by the function name and any parameter list, as shown below:
function(<function_name> [arg1 [arg2 [...]]])
# Function code...
endfunction()
The function name should be unique to avoid conflicts with other functions. The code between the function()
and endfunction()
keywords is the function code block.
The parameter list here is optional; you can define zero, one, or multiple parameters for your function. Note that the parameter list in the function call is space-separated, so each argument will automatically map to the parameters defined.
Using ARGN and ARGC
Two special variables in CMake, ARGN
and ARGC
, are particularly useful for handling function parameters.
- ARGN: This variable contains all unnamed parameters passed to the function call. It is useful for handling an uncertain number of parameters.
- ARGC: This variable contains the total number of parameters passed to the function.
Calling Functions
To call a CMake function, simply use the function name and pass the required parameters. When calling the function, the parameter names defined in the actual parameter list will be bound to the parameter values passed during the function call.
<function_name>([arg1 [arg2 [...]]])
Example:
# Define a simple function that takes two parameters and outputs them
function(print_args ARG1 ARG2)
message("Argument 1 is '${ARG1}'")
message("Argument 2 is '${ARG2}'")
endfunction()
# Call the print_args function
print_args("Hello" "World")
# Output:
# Argument 1 is 'Hello'
# Argument 2 is 'World'
# An example of a function that handles an uncertain number of parameters
function(print_multiple_args)
set(NumArgs ${ARGC})
message("Total number of arguments: ${NumArgs}")
foreach(Arg ${ARGN})
message("Arg: '${Arg}'")
endforeach()
endfunction()
# Call the print_multiple_args function
print_multiple_args("arg1" "arg2" "arg3")
# Output:
# Total number of arguments: 3
# Arg: 'arg1'
# Arg: 'arg2'
# Arg: 'arg3'
Practicing on a computer will help better understand CMake functions and how to define and call them.