Last active
December 27, 2022 08:17
-
-
Save mrowrpurr/cfe032043feea57b1c58bcf63ce10f43 to your computer and use it in GitHub Desktop.
CMake - Argumen Parser Helper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Note: this parser | |
# Here is the helper macro to use in your project: | |
macro(parse_arguments) | |
cmake_parse_arguments(__argument_parser "" "PREFIX" "FLAG;VALUE;MULTI;ARGS" ${ARGN}) | |
if(NOT DEFINED __argument_parser_PREFIX) | |
set(__argument_parser_PREFIX "${CMAKE_CURRENT_FUNCTION}") | |
endif() | |
cmake_parse_arguments("${__argument_parser_PREFIX}" "${__argument_parser_FLAG}" "${__argument_parser_VALUE}" "${__argument_parser_MULTI}" ${__argument_parser_ARGS}) | |
set(arg_prefix "${__argument_parser_PREFIX}_") | |
endmacro() | |
# Here is example usage: | |
function(my_function ARG1) | |
message("ARG1 is ${ARG1}") | |
parse_arguments( | |
FLAG IS_FOO NOT_BAR # (optional) provide FLAG arguments, if any | |
VALUE NAME TARGET # (optional) provide single VALUE arguments, if any | |
MULTI FILES SOURCES # (optional) provide MULTI arguments which can have pass multiple values, if any | |
ARGS ${ARGN} # (required) provide ARGN (additional arguments passed to the function/macro) | |
) | |
message("Name: ${${arg_prefix}NAME}") # Just prefix each argument with ${arg_prefix} when accessing it | |
endfunction() | |
# Call the function normally: | |
my_function("Whatever" IS_FOO FILES a.txt b.txt c.txt NAME CoolName) | |
# You NEVER need to provide a "PREFIX" using this helper. It defaults to the name of the current function. | |
# Note: in macros, it'll also default to the name of the current *function*. | |
# If you ever want/need to set the previs manually, just pass PREFIX "Something". You can still use ${arg_prefix}. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment