Eric Sommerlade
Overview > Misc > Optional arguments to CMake functions

Optional arguments to CMake functions

I have been looking for an example for optional function arguments to CMake functions.It's pretty simple, you just don't add a name to the argument list, and reference the argument only by ${ARGVx}, where x is the number of the argument in the list, minus the function name and starting from zero.


function(make_test MODULE_NAME)
add_executable(test_${MODULE_NAME} src/test_${MODULE_NAME}.cpp
src/${MODULE_NAME}.cpp ${ARGV1})

This adds an executable to your project using the module name and optional source files in a second argument, e.g. after a call to

make_test(svd src/matrix.cpp)


you'd end up with test_svd depending on src/test_svd.cpp, src/svd.cpp, and src/matrix.cpp plus test_matrix, depending on src/test_matrix.cpp, and src/matrix.cpp.