Skip to content
The Chat Archive
Claudeclaude-opus-4-20250514· AnthropicHugging Face LMArena Human Preference 140K

how to configure a cmake function to have a named argument which can be undefined (so…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Qwenqwen3-235b-a22b-no-thinking’s answer.
  1. User

    how to configure a cmake function to have a named argument which can be undefined (so not used when calling the function), an empty string or a non-empty string? how to differentiate between being undefined or empty?

  2. Claude Assistant

    In CMake, you can create functions with named arguments using cmake_parse_arguments(). Here's how to handle an argument that can be undefined, empty, or have a value:

    function(my_function)
        # Define argument categories
        set(options "")  # Boolean flags
        set(oneValueArgs MY_ARG)  # Single-value arguments
        set(multiValueArgs "")  # Multi-value arguments
        
        # Parse arguments
        cmake_parse_arguments(PARSE_ARGV 0 ARG "${options}" "${oneValueArgs}" "${multiValueArgs}")
        
        # Check if MY_ARG was provided at all
        if(DEFINED ARG_MY_ARG)
            # Argument was provided
            if("${ARG_MY_ARG}" STREQUAL "")
                message("MY_ARG was provided but is empty")
            else()
                message("MY_ARG was provided with value: ${ARG_MY_ARG}")
            endif()
        else()
            # Argument was not provided
            message("MY_ARG was not provided")
        endif()
    endfunction()
    
    # Usage examples:
    my_function()                          # MY_ARG undefined
    my_function(MY_ARG "")                 # MY_ARG empty
    my_function(MY_ARG "some_value")       # MY_ARG with value
    

    The key distinction is:

    • Undefined: The variable ARG_MY_ARG is not defined at all (check with if(DEFINED ARG_MY_ARG))
    • Empty: The variable exists but contains an empty string (check with if("${ARG_MY_ARG}" STREQUAL ""))

    You can also use a more defensive approach with additional checks:

    function(my_function_safe)
        set(oneValueArgs MY_ARG)
        cmake_parse_arguments(PARSE_ARGV 0 ARG "" "${oneValueArgs}" "")
        
        if(DEFINED ARG_MY_ARG)
            if(NOT ARG_MY_ARG)  # Checks for empty/false/0
                message("MY_ARG is empty or false")
            else()
                message("MY_ARG has value: ${ARG_MY_ARG}")
            endif()
        else()
            message("MY_ARG is undefined")
        endif()
    endfunction()
    

    Note that cmake_parse_arguments() with PARSE_ARGV requires CMake 3.7+. For older versions, you'd use the legacy syntax with ${ARGN}.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.