例如,我想使用以下语法编写my_add_lib
函数:
my_add_lib(NAME <name>
SRCS [src1 [src2 ...]]
DEPS [dependency1 [dependancy2 ...]]])
如何实现这些“参数组”?
答案 0 :(得分:15)
CMake提供CMakeParseArguments模块,可以为您解析参数。例如:
include(CMakeParseArguments)
function(my_add_lib)
cmake_parse_arguments(
PARSED_ARGS # prefix of output variables
"" # list of names of the boolean arguments (only defined ones will be true)
"NAME" # list of names of mono-valued arguments
"SRCS;DEPS" # list of names of multi-valued arguments (output variables are lists)
${ARGN} # arguments of the function to parse, here we take the all original ones
)
# note: if it remains unparsed arguments, here, they can be found in variable PARSED_ARGS_UNPARSED_ARGUMENTS
if(NOT PARSED_ARGS_NAME)
message(FATAL_ERROR "You must provide a name")
endif(NOT PARSED_ARGS_NAME)
message("Provided sources are:")
foreach(src ${PARSED_ARGS_SRCS})
message("- ${src}")
endforeach(src)
endfunction(my_add_lib)
从CMake 3.5开始,cmake_parse_arguments
成为内置命令(用C ++而不是CMake编写):不再需要include(CMakeParseArguments)
但是,目前,文件CMakeParseArguments.cmake保持为空以保持兼容性