How to write a cmake function with more than one parameter groups?

StackOverflow https://stackoverflow.com/questions/23327687

  •  10-07-2023
  •  | 
  •  

Вопрос

For example, I want write a my_add_lib function with the following syntax:

my_add_lib(NAME <name>
           SRCS [src1 [src2 ...]]
           DEPS [dependency1 [dependency2 ...]]])

How to do implement these "parameter group"?

Это было полезно?

Решение

CMake provides CMakeParseArguments module which can do arguments parsing for you. Example:

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)

As of CMake 3.5, cmake_parse_arguments becomes a builtin command (written in C++ instead of CMake): include(CMakeParseArguments) is no longer required but, for now, the file CMakeParseArguments.cmake is kept empty for compatibility.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top