### Add Example Executables using Custom Function Source: https://github.com/fredemmott/magic_args/blob/master/examples/CMakeLists.txt Demonstrates the usage of the `add_example` function to define several example executables, such as 'example-minimal', 'example-minimal-powershell-style', and 'example-everything'. ```cmake add_example(example-minimal minimal.cpp) add_example(example-minimal-powershell-style minimal-powershell-style.cpp) add_example(example-everything everything.cpp) ``` -------------------------------- ### CMake Build Configuration for Tests and Examples Source: https://github.com/fredemmott/magic_args/blob/master/CMakeLists.txt Configures CMake to conditionally build testing and example components based on user-defined options. It includes subdirectories for these components if they are enabled. ```cmake add_subdirectory(magic_args) option(BUILD_TESTING "Build tests" "${PROJECT_IS_TOP_LEVEL}") if (BUILD_TESTING) include(CTest) add_subdirectory(tests) endif () option(BUILD_EXAMPLES "Build examples" "${PROJECT_IS_TOP_LEVEL}") if (BUILD_EXAMPLES) add_subdirectory(examples) endif () ``` -------------------------------- ### Install Single-Header Version (CMake) Source: https://github.com/fredemmott/magic_args/blob/master/magic_args/CMakeLists.txt This snippet defines the installation rule for the generated single-header file, making it available under the 'SingleHeader' component. ```cmake install( FILES "${SINGLE_HEADER_OUTPUT_FILE}" DESTINATION "include/magic_args" COMPONENT SingleHeader EXCLUDE_FROM_ALL ) ``` -------------------------------- ### Install magic_args Library and Exports (CMake) Source: https://github.com/fredemmott/magic_args/blob/master/magic_args/CMakeLists.txt This configuration block handles the installation of the main magic_args library, its headers, and the CMake export files required for package management. ```cmake install( TARGETS magic_args EXPORT exports FILE_SET HEADERS DESTINATION include/magic_args ) install( EXPORT exports NAMESPACE magic_args:: FILE magic_args-targets.cmake DESTINATION lib/cmake/magic_args ) install( FILES "${CMAKE_CURRENT_SOURCE_DIR}/magic_args-config.cmake" DESTINATION lib/cmake/magic_args ) ``` -------------------------------- ### Define Custom CMake Function to Add Examples Source: https://github.com/fredemmott/magic_args/blob/master/examples/CMakeLists.txt This CMake function simplifies adding new examples. It takes a target name and source files, then creates an executable linked against the magic_args library. It supports variadic arguments for source files. ```cmake function(add_example TARGET) add_executable("${TARGET}" ${ARGN}) target_link_libraries("${TARGET}" PRIVATE magic_args) endfunction() ``` -------------------------------- ### Configure Windows-Specific Example Build Source: https://github.com/fredemmott/magic_args/blob/master/examples/CMakeLists.txt Conditionally adds the 'example-windows' executable for Windows platforms. It links against magic_args, defines UNICODE and _UNICODE preprocessor macros, and applies UTF-8 compilation flags if using MSVC. ```cmake if (WIN32) add_example(example-windows WIN32 windows.cpp "${CMAKE_SOURCE_DIR}/tests/utf8-process-code-page.manifest") target_compile_definitions( example-windows PRIVATE UNICODE _UNICODE ) if (MSVC) target_compile_options( example-windows PRIVATE /utf-8 ) endif () endif () ``` -------------------------------- ### CMake Project Setup and Compiler Options Source: https://github.com/fredemmott/magic_args/blob/master/CMakeLists.txt Initializes the CMake project, sets the minimum version, and defines compiler flags for MSVC and Clang-CL. These options control warning levels, error reporting, and character encoding. ```cmake cmake_minimum_required(VERSION 3.22..3.29) project(magic_args VERSION 0.2.1 LANGUAGES CXX) if (MSVC) add_compile_options( # Include content and marker in error messages "/diagnostics:caret" # Source is UTF-8 "/utf-8" ) if (PROJECT_IS_TOP_LEVEL) add_compile_options( # C++ standard exception handling "/EHsc" # Enable most warnings "/W4" # Error on warning "/WX" ) # Clang-CL if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") add_compile_options( "-Wno-missing-field-initializers" "-Wno-missing-designated-field-initializers" # As of 2025-02-13, the version of Clang-CL on GitHub actions does not recognize # -Wno-missing-designated-field-initializers "-Wno-unknown-warning-option" ) endif () endif () endif () ``` -------------------------------- ### C++: Complete magic_args Feature Example Source: https://context7.com/fredemmott/magic_args/llms.txt This example demonstrates the comprehensive features of the magic_args library, including flags, options with default values, optional arguments, custom types, mandatory and optional positional arguments, and multi-value arguments. It also shows how to provide program information like description, version, and examples, and how to handle parsing results and errors. ```cpp #include using namespace magic_args::public_api; struct CustomType { std::string mValue; }; void from_string_argument(CustomType& value, std::string_view arg) { value.mValue = arg; } std::string formattable_argument_value(const CustomType& value) { return value.mValue; } struct MyArgs { flag mFlag { .mName = "flag", .mHelp = "Enable flag mode", }; option mConfiguredString { "default", "configured-string", "A parameter with documentation", "c", }; option> mConfiguredOptional { .mValue = "default", .mName = "configured-optional", .mHelp = "Where empty != absent", .mShortName = "o", }; std::optional mOptionalString; int mNumber {0}; CustomType mCustomType; mandatory_positional_argument mMandatoryPos { {}, "INPUT", "Mandatory input file", }; optional_positional_argument mOptionalPos { .mValue = "default.txt", }; optional_positional_argument> mMulti {}; }; int main(int argc, char** argv) { const magic_args::program_info info { .mDescription = "Demonstrates all library features", .mVersion = "v1.0.0", .mExamples = { "example INPUT", "example --flag -c value INPUT output.txt extra1 extra2", }, }; const auto args = magic_args::parse(argc, argv, info); if (!args.has_value()) { switch (args.error()) { case HelpRequested: case VersionRequested: return EXIT_SUCCESS; default: return EXIT_FAILURE; } } magic_args::dump(*args); return EXIT_SUCCESS; } ``` -------------------------------- ### Program Information and Parsing in C++ Source: https://github.com/fredemmott/magic_args/blob/master/README.md Illustrates how to define program-level information such as description, version, and examples for use with magic_args. It also shows the basic parsing call with program information. ```c++ const magic_args::program_info programInfo { .mDescription = "My program does something", .mVersion = "HerpDerp v1.0.0", .mExamples = { "myprog FOO", "myprog FOO --bar", }, }; const auto args = magic_args::parse(argc, argv, programInfo); ``` -------------------------------- ### Enable PowerShell-Style Argument Parsing in C++ with Magic Args Source: https://context7.com/fredemmott/magic_args/llms.txt This example demonstrates how to use PowerShell-style argument parsing, which supports single-dash flags and UpperCamelCase names, by passing `powershell_style_parsing_traits` to `magic_args::parse`. It requires the `` header. ```cpp #include using namespace magic_args::public_api; struct MyArgs { bool mVerbose {false}; std::string mOutputPath; int mMaxRetries {3}; }; int main(int argc, char** argv) { const auto args = magic_args::parse< MyArgs, powershell_style_parsing_traits>(argc, argv); if (!args.has_value()) { return EXIT_FAILURE; } magic_args::dump(*args); return EXIT_SUCCESS; } // Usage: // $ ./program -Verbose -OutputPath result.txt -MaxRetries 5 // mVerbose `true` // mOutputPath `result.txt` // mMaxRetries `5` // // $ ./program -Help // Usage: program [OPTIONS...] // // Options: // // -Verbose // -OutputPath=VALUE // -MaxRetries=VALUE // // -?, -Help show this message ``` -------------------------------- ### Generate Program Help Text with Magic Args (C++) Source: https://context7.com/fredemmott/magic_args/llms.txt Illustrates how to enhance command-line argument parsing with program-specific information like descriptions, version numbers, and usage examples using `magic_args`. The `magic_args::program_info` struct is populated and passed to `magic_args::parse`, influencing the output of the help and version flags. Error handling for help and version requests is also shown. ```cpp #include using namespace magic_args::public_api; struct MyArgs { flag mRecursive { .mName = "recursive", .mHelp = "Process directories recursively", .mShortName = "r", }; option mFormat { .mValue = "json", .mName = "format", .mHelp = "Output format (json, xml, csv)", .mShortName = "f", }; mandatory_positional_argument mPath { {}, "PATH", "Directory path to analyze", }; }; int main(int argc, char** argv) { const magic_args::program_info programInfo { .mDescription = "Analyzes directory structure and generates reports", .mVersion = "diranalyze v2.1.0", .mExamples = { "diranalyze /home/user/documents", "diranalyze -r /var/log", "diranalyze --format xml --recursive /etc", }, }; const auto args = magic_args::parse(argc, argv, programInfo); if (!args.has_value()) { switch (args.error()) { case HelpRequested: case VersionRequested: return EXIT_SUCCESS; default: return EXIT_FAILURE; } } printf("Analyzing: %s (format: %s, recursive: %s)\n", args->mPath.mValue.c_str(), args->mFormat.mValue.c_str(), args->mRecursive ? "yes" : "no"); return EXIT_SUCCESS; } // Usage: // $ ./program --help // Usage: program [OPTIONS...] PATH // Analyzes directory structure and generates reports. // // Examples: // // diranalyze /home/user/documents // diranalyze -r /var/log // diranalyze --format xml --recursive /etc // // Options: // // -r, --recursive Process directories recursively // -f, --format=VALUE Output format (json, xml, csv) // // -?, --help show this message // --version print program version // // Arguments: // // PATH Directory path to analyze // // $ ./program --version // diranalyze v2.1.0 ``` -------------------------------- ### Windows `WinMain`/`wWinMain` Support in C++ Source: https://github.com/fredemmott/magic_args/blob/master/README.md Provides guidance and code examples for using magic_args with Windows-specific entry points (`WinMain`, `wWinMain`) when a standard `main` is not feasible. It highlights the use of `GetCommandLineW()` and UTF-8 encoding. ```c++ #define MAGIC_ARGS_ENABLE_WINDOWS_EXTENSIONS #include // If you're not using the single-header version, you can do this instead of using the macro: #include ... magic_args::attach_to_parent_terminal(); const auto args = magic_args::parse(GetCommandLineW()); ``` -------------------------------- ### Use Verbatim Member Names for Argument Parsing in C++ with Magic Args Source: https://context7.com/fredemmott/magic_args/llms.txt This example demonstrates disabling automatic argument name inference and using struct member names exactly as defined by employing `verbatim_names`. This ensures exact matching between command-line arguments and struct members. It requires the `` header. ```cpp #include using namespace magic_args::public_api; struct MyArgs { bool verbose {false}; std::string output_file; int max_connections {100}; }; int main(int argc, char** argv) { const auto args = magic_args::parse< MyArgs, verbatim_names>(argc, argv); if (!args.has_value()) { return EXIT_FAILURE; } magic_args::dump(*args); return EXIT_SUCCESS; } // Usage: // $ ./program --verbose --output_file log.txt --max_connections 200 // verbose `true` // output_file `log.txt` // max_connections `200` // // $ ./program --help // Usage: program [OPTIONS...] // // Options: // // --verbose // --output_file=VALUE // --max_connections=VALUE // // -?, --help show this message ``` -------------------------------- ### Parse Positional Arguments with Magic Args (C++) Source: https://context7.com/fredemmott/magic_args/llms.txt Demonstrates parsing mandatory, optional, and multi-value positional arguments using the magic_args library. It defines a struct to hold argument types and uses `magic_args::parse` to process command-line inputs. The example shows how to access parsed values and handle potential parsing errors. ```cpp #include using namespace magic_args::public_api; struct MyArgs { mandatory_positional_argument mInput { {}, "INPUT", "Input file to process", }; optional_positional_argument mOutput { .mValue = "output.txt", .mName = "OUTPUT", .mHelp = "Output file (default: output.txt)", }; optional_positional_argument> mExtra { {}, "EXTRA", "Additional files to include", }; }; int main(int argc, char** argv) { const auto args = magic_args::parse(argc, argv); if (!args.has_value()) { return EXIT_FAILURE; } printf("Input: %s\n", args->mInput.mValue.c_str()); printf("Output: %s\n", args->mOutput.mValue.c_str()); if (!args->mExtra.mValue.empty()) { printf("Extra files:\n"); for (const auto& file : args->mExtra.mValue) { printf(" - %s\n", file.c_str()); } } return EXIT_SUCCESS; } // Usage: // $ ./program input.dat // Input: input.dat // Output: output.txt // // $ ./program input.dat result.dat extra1.dat extra2.dat // Input: input.dat // Output: result.dat // Extra files: // - extra1.dat // - extra2.dat // // $ ./program --help // Usage: program [OPTIONS...] INPUT [OUTPUT] [EXTRA...] // // Options: // -?, --help show this message // // Arguments: // INPUT Input file to process // OUTPUT Output file (default: output.txt) // EXTRA Additional files to include ``` -------------------------------- ### Create Executable Target and Link Libraries Source: https://github.com/fredemmott/magic_args/blob/master/tests/CMakeLists.txt Creates an executable target 'split-header-tests' and links it with 'test-lib', Catch2, and 'magic_args'. It also conditionally includes platform-specific source files for Windows. ```cmake add_executable(split-header-tests test.cpp test-styles.cpp) target_link_libraries(split-header-tests PRIVATE test-lib Catch2::Catch2 Catch2::Catch2WithMain magic_args) if (WIN32) target_sources(split-header-tests PRIVATE test-windows.cpp utf8-process-code-page.manifest) endif () ``` -------------------------------- ### Create Single-Header Executable Target and Link Libraries Source: https://github.com/fredemmott/magic_args/blob/master/tests/CMakeLists.txt Creates an executable target 'single-header-tests' and links it with 'test-lib', Catch2, and 'magic_args-single-header'. It also conditionally includes platform-specific source files for Windows. ```cmake add_executable(single-header-tests test.cpp test-styles.cpp) target_link_libraries(single-header-tests PRIVATE test-lib Catch2::Catch2 Catch2::Catch2WithMain magic_args-single-header) if (WIN32) target_sources(single-header-tests PRIVATE test-windows.cpp utf8-process-code-page.manifest) endif () ``` -------------------------------- ### Find and Configure Catch2 Testing Framework Source: https://github.com/fredemmott/magic_args/blob/master/tests/CMakeLists.txt Finds the Catch2 testing framework and configures it to discover tests for the specified executable targets. It includes the necessary Catch2 CMake script. ```cmake find_package(Catch2 CONFIG REQUIRED) include("${Catch2_DIR}/Catch.cmake") catch_discover_tests(split-header-tests single-header-tests) ``` -------------------------------- ### Generate Single-Header Version (CMake) Source: https://github.com/fredemmott/magic_args/blob/master/magic_args/CMakeLists.txt This section configures the creation of a single-header file from the library's source files. It defines the output path and uses a custom command to concatenate files. ```cmake set(SINGLE_HEADER_SOURCES "${HEADER_FILES}") list(PREPEND SINGLE_HEADER_SOURCES detail/single_header_prefix.hpp) set(SINGLE_HEADER_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/$/single-header/magic_args") set(SINGLE_HEADER_OUTPUT_FILE "${SINGLE_HEADER_OUTPUT_DIRECTORY}/magic_args.hpp") add_custom_command( OUTPUT "${SINGLE_HEADER_OUTPUT_FILE}" COMMAND "${CMAKE_COMMAND}" -E make_directory "${SINGLE_HEADER_OUTPUT_DIRECTORY}" COMMAND "${CMAKE_COMMAND}" -E cat "${SINGLE_HEADER_SOURCES}" > "${SINGLE_HEADER_OUTPUT_FILE}" DEPENDS "${SINGLE_HEADER_SOURCES}" "${CMAKE_CURRENT_LIST_FILE}" WORKING_DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}" VERBATIM COMMAND_EXPAND_LISTS ) ``` -------------------------------- ### Define magic_args Interface Library (CMake) Source: https://github.com/fredemmott/magic_args/blob/master/magic_args/CMakeLists.txt This snippet defines the main interface library for magic_args. It specifies header files, include directories, and the required C++ standard. ```cmake add_library(magic_args INTERFACE) set( HEADER_FILES # DO NOT SORT THESE # # These are in the order required for the single-header version detail/concepts.hpp detail/reflection.hpp gnu_style_parsing_traits.hpp powershell_style_parsing_traits.hpp detail/print.hpp argument_definitions.hpp detail/get_argument_definition.hpp detail/validation.hpp program_info.hpp detail/usage.hpp incomplete_parse_reason.hpp detail/parse.hpp dump.hpp parse.hpp verbatim_names.hpp magic_args.hpp windows.hpp ) target_sources( magic_args INTERFACE FILE_SET HEADERS TYPE HEADERS FILES ${HEADER_FILES} ) target_include_directories( magic_args INTERFACE "$" "$" ) target_compile_features( magic_args INTERFACE cxx_std_23 ) ``` -------------------------------- ### Define magic_args-single-header Interface Library (CMake) Source: https://github.com/fredemmott/magic_args/blob/master/magic_args/CMakeLists.txt This snippet defines an interface library for the generated single-header file. It points to the generated file and sets the include directories and C++ standard. ```cmake add_library( magic_args-single-header INTERFACE "${SINGLE_HEADER_OUTPUT_FILE}" ) target_include_directories( magic_args-single-header INTERFACE "${SINGLE_HEADER_OUTPUT_DIRECTORY}/.." ) target_compile_features( magic_args-single-header INTERFACE cxx_std_23 ) ``` -------------------------------- ### Define Static Library Target with C++23 Source: https://github.com/fredemmott/magic_args/blob/master/tests/CMakeLists.txt Defines a static library named 'test-lib' and sets the C++ standard to C++23. It conditionally includes platform-specific source files based on the WIN32 macro. ```cmake add_library( test-lib STATIC output.cpp output.hpp ) target_compile_features( test-lib PUBLIC cxx_std_23 ) if (WIN32) target_sources(test-lib PRIVATE output-windows.cpp) else () target_sources(test-lib PRIVATE output-posix.cpp) endif () ``` -------------------------------- ### Basic Argument Parsing with magic_args Source: https://context7.com/fredemmott/magic_args/llms.txt Demonstrates fundamental command-line argument parsing using magic_args. It automatically infers argument names from struct member names, handles basic types like bool, string, and int, and generates help text. Requires C++23 and the standard library. ```cpp #include struct MyArgs { bool mFoo {false}; std::string mBar; int mBaz {0}; }; int main(int argc, char** argv) { const std::expected args = magic_args::parse(argc, argv); if (!args.has_value()) { if (args.error() == magic_args::HelpRequested) { return EXIT_SUCCESS; } return EXIT_FAILURE; } magic_args::dump(*args); return EXIT_SUCCESS; } // Usage: // $ ./program --foo --bar SomeString --baz=123 // mFoo `true` // mBar `SomeString` // mBaz `123` // // $ ./program --help // Usage: program [OPTIONS...] // // Options: // // --foo // --bar=VALUE // --baz=VALUE // // -?, --help show this message ``` -------------------------------- ### Create Alias for add_subdirectory (CMake) Source: https://github.com/fredemmott/magic_args/blob/master/magic_args/CMakeLists.txt This establishes an alias target for the magic_args library, allowing projects using `add_subdirectory` to refer to it conveniently. ```cmake # For projects using add_subdirectory() add_library(magic_args::magic_args ALIAS magic_args) ``` -------------------------------- ### Customized Options with Short Flags in magic_args Source: https://context7.com/fredemmott/magic_args/llms.txt Illustrates how to customize command-line options in magic_args, including setting custom names, help text, and short flags using `option<>` and `flag` types. This provides a more user-friendly command-line interface. Requires C++23. ```cpp #include using namespace magic_args::public_api; struct MyArgs { flag mVerbose { .mName = "verbose", .mHelp = "Enable verbose output", .mShortName = "v", }; option mOutput { .mValue = "output.txt", .mName = "output", .mHelp = "Output file path", .mShortName = "o", }; option mThreads { .mValue = 4, .mName = "threads", .mHelp = "Number of worker threads", .mShortName = "j", }; }; int main(int argc, char** argv) { const auto args = magic_args::parse(argc, argv); if (!args.has_value()) { return (args.error() == HelpRequested) ? EXIT_SUCCESS : EXIT_FAILURE; } if (args->mVerbose) { printf("Output: %s, Threads: %d\n", args->mOutput.mValue.c_str(), args->mThreads.mValue); } return EXIT_SUCCESS; } // Usage: // $ ./program -v -o results.txt -j 8 // Output: results.txt, Threads: 8 // // $ ./program --help // Usage: program [OPTIONS...] // // Options: // // -v, --verbose Enable verbose output // -o, --output=VALUE Output file path // -j, --threads=VALUE Number of worker threads // -?, --help show this message ``` -------------------------------- ### Positional Arguments with Defaults and Docs in C++ Source: https://github.com/fredemmott/magic_args/blob/master/README.md Shows how to provide default values, names, and help documentation for mandatory positional arguments using magic_args. This allows for more user-friendly command-line interfaces. ```c++ struct MyArgs { magic_args::mandatory_positional_argument mPos1 { .mValue = "default", .mName = "POSITIONAL", .mHelp = "help text here", }; }; ``` -------------------------------- ### Integrate Magic Args with Windows WinMain for GUI Apps in C++ Source: https://context7.com/fredemmott/magic_args/llms.txt This snippet shows how to parse command-line arguments within Windows GUI applications using `WinMain` or `wWinMain`. It requires defining `MAGIC_ARGS_ENABLE_WINDOWS_EXTENSIONS` before including the header and uses `GetCommandLineW()` for parsing. ```cpp #define MAGIC_ARGS_ENABLE_WINDOWS_EXTENSIONS #include struct MyArgs { bool mFullscreen {false}; int mWidth {1024}; int mHeight {768}; }; int WINAPI wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPWSTR lpCmdLine, int nCmdShow) { magic_args::attach_to_parent_terminal(); const auto args = magic_args::parse(GetCommandLineW()); if (!args.has_value()) { if (args.error() == magic_args::HelpRequested) { return EXIT_SUCCESS; } return EXIT_FAILURE; } // Initialize window with parsed arguments CreateWindowEx( 0, L"MainWindow", L"My App", args->mFullscreen ? WS_POPUP : WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, args->mWidth, args->mHeight, nullptr, nullptr, hInstance, nullptr); magic_args::dump(*args); return EXIT_SUCCESS; } // Usage: // > app.exe -fullscreen -width 1920 -height 1080 // mFullscreen `true` // mWidth `1920` // mHeight `1080` ``` -------------------------------- ### Handling Version Request in C++ Source: https://github.com/fredemmott/magic_args/blob/master/README.md Explains how to handle the `magic_args::VersionRequested` exception, similar to `HelpRequested`, which occurs when the user requests the program version using the `--version` flag. ```c++ // If you provide a version, `parse<>()` can result in `std::unexpected{ magic_args::VersionRequested }`; // like `HelpRequested`, you will probably want to return `EXIT_SUCCESS` from `main()` for this. ``` -------------------------------- ### Customizing Options and Flags in C++ Source: https://github.com/fredemmott/magic_args/blob/master/README.md Demonstrates how to customize argument options and flags using `magic_args::option<>` and `magic_args::flag<>`. This allows specifying custom names, help text, and short flags for greater control over the command-line interface. ```c++ struct MyArgs { magic_args::flag mMyFlag { .mName = "long-name", // --my-flag .mHelp = "documentation here", .mShortName = "m", // -m }; magic_args::option mOpt1 { .mValue = "default", .mName = "option", // --option .mHelp = "documentation here", .mShortName = "o", // -m }; magic_args::option mOpt2 { {}, "option-2", "documentation", "p" }; }; ``` -------------------------------- ### Handling Optional Arguments with std::optional in magic_args Source: https://context7.com/fredemmott/magic_args/llms.txt Demonstrates how to use `std::optional` with magic_args to differentiate between an argument that was not provided and one that was provided with a default value. This enhances flexibility in argument handling. Requires C++23. ```cpp #include using namespace magic_args::public_api; struct MyArgs { std::optional mConfig; option> mTimeout { .mValue = std::nullopt, .mName = "timeout", .mHelp = "Request timeout in seconds", }; }; int main(int argc, char** argv) { const auto args = magic_args::parse(argc, argv); if (!args.has_value()) { return EXIT_FAILURE; } if (args->mConfig.has_value()) { printf("Loading config from: %s\n", args->mConfig->c_str()); } else { printf("Using default configuration\n"); } if (args->mTimeout.has_value()) { printf("Timeout set to: %d seconds\n", *args->mTimeout); } else { printf("No timeout specified, waiting indefinitely\n"); } return EXIT_SUCCESS; } // Usage: // $ ./program // Using default configuration // No timeout specified, waiting indefinitely // // $ ./program --config app.cfg --timeout 30 // Loading config from: app.cfg // Timeout set to: 30 seconds ``` -------------------------------- ### Basic Argument Parsing in C++ Source: https://github.com/fredemmott/magic_args/blob/master/README.md Demonstrates the core functionality of magic_args for parsing command-line arguments into a struct. It shows how to include the library, define a struct for arguments, parse them, and handle help requests or errors. ```c++ #include struct MyArgs { bool mFoo {false}; std::string mBar; int mBaz {0}; }; int main(int argc, char** argv) { // This gets you an // std::expected const auto args = magic_args::parse(argc, argv); if (!args.has_value()) { if (args.error() == magic_args::HelpRequested) { return EXIT_SUCCESS; } return EXIT_FAILURE; } magic_args::dump(*args); return EXIT_SUCCESS; } ``` -------------------------------- ### Implement Custom IPAddress Type for Argument Parsing in C++ Source: https://context7.com/fredemmott/magic_args/llms.txt This snippet shows how to define a custom IPAddress type that can be parsed from string arguments using `from_string_argument` and formatted back to a string with `formattable_argument_value`. It requires the `` header and uses `std::regex` for validation. ```cpp #include #include struct IPAddress { uint8_t octets[4]; }; void from_string_argument(IPAddress& value, std::string_view arg) { std::regex pattern(R"((\d+)\.(\d+)\.(\d+)\.(\d+))"); std::string str(arg); std::smatch match; if (!std::regex_match(str, match, pattern)) { throw std::invalid_argument("Invalid IP address format"); } for (int i = 0; i < 4; ++i) { int octet = std::stoi(match[i + 1]); if (octet < 0 || octet > 255) { throw std::out_of_range("IP octet out of range"); } value.octets[i] = static_cast(octet); } } std::string formattable_argument_value(const IPAddress& value) { return std::format("{}.{}.{}.{}", value.octets[0], value.octets[1], value.octets[2], value.octets[3]); } struct MyArgs { IPAddress mServerIP; int mPort {8080}; }; int main(int argc, char** argv) { const auto args = magic_args::parse(argc, argv); if (!args.has_value()) { return EXIT_FAILURE; } magic_args::dump(*args); return EXIT_SUCCESS; } // Usage: // $ ./program --server-ip 192.168.1.100 --port 3000 // mServerIP `192.168.1.100` // mPort `3000` ``` -------------------------------- ### PowerShell-Style Parsing Traits in C++ Source: https://github.com/fredemmott/magic_args/blob/master/README.md Demonstrates how to enable PowerShell-like argument parsing syntax in magic_args using `magic_args::powershell_style_parsing_traits`. This changes argument formatting and naming conventions. ```c++ const auto args = magic_args::parse< MyArgs, magic_args::powershell_style_parsing_traits>(argc, argv); ``` -------------------------------- ### Define Positional Arguments in C++ Source: https://github.com/fredemmott/magic_args/blob/master/README.md Demonstrates how to define mandatory and optional positional arguments using magic_args. It covers basic types like std::string and std::vector, along with constraints on their usage (e.g., vector must be last, no multiple vectors). ```c++ struct MyArgs { magic_args::mandatory_positional_argument mPos1; magic_args::optional_positional_argument mPos2; magic_args::optional_positional_argument> mPos3; }; ``` -------------------------------- ### Custom Argument Type Support in C++ Source: https://github.com/fredemmott/magic_args/blob/master/README.md Details the requirements for supporting custom argument types with magic_args. This involves implementing `from_string_argument` for parsing and `formattable_argument_value` (or `std::formatter`) for output. ```c++ // Used by `magic_args::parse()` void from_string_argument(T& v, std::string_view arg); // Used by `magic_args::dump()`; alternatively, implement `std::formatter<>` auto formattable_argument_value(const T& v); ``` -------------------------------- ### Verbatim Argument Name Parsing in C++ Source: https://github.com/fredemmott/magic_args/blob/master/README.md Shows how to disable automatic argument name inference and use struct member names verbatim. This is achieved using the `verbatim_names<>` helper with either GNU or PowerShell style parsing traits. ```c++ const auto args = magic_args::parse< MyArgs, magic_args::verbatim_names>(argv); // ... or ... const auto args = magic_args::parse< MyArgs, magic_args::verbatim_names>(argv); ``` -------------------------------- ### Argument Name Inference in C++ Source: https://github.com/fredemmott/magic_args/blob/master/README.md Illustrates how magic_args automatically infers long argument names from struct member names. It covers various naming conventions like UpperCamelCase, underscore_snake_case, and lowerCamelCase. ```c++ struct MyArgs { std::string mEmUpperCamel; std::string m_EmUnderscoreUpperCamel; std::string _UnderscoreUpperCamel; std::string _underscoreLowerCamel; std::string UpperCamel; std::string lowerCamel; std::string m_em_snake_case; std::string snake_case; }; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.