kaycxx-cli
C++ CLI library
Loading...
Searching...
No Matches
Parsing and Errors

app::parse accepts argc and argv directly from main and returns the parsed arguments.

auto arguments = example.parse(argc, argv);

The returned args object is movable but not copyable. Keep it by value with auto.

Flags and options are parsed immediately. Unknown switches, missing or invalid option values, and conflicting actions therefore produce an error during parse().

Whether required options were supplied is validated lazily. This keeps help and version actions usable without otherwise mandatory input.

Positional arguments are retained as strings and validated lazily. Accessing any positional parameter through args::get() or args::has() validates and converts all positional parameters once.

Subcommands are selected while parsing. An unknown command therefore produces an immediate error. A missing subcommand is validated lazily so help and other actions can be handled for the current command first.

Explicit Validation

Call args::validate() to validate required options, subcommands and positional parameters without reading one of them.

arguments.validate();

This is useful when a command defines positional parameters but does not otherwise access every execution path through their handles. Calling validate() repeatedly has no effect after the first successful validation.

Argument Order

Flags, options, and positional arguments may be freely mixed within one command. Selecting a subcommand changes the active command scope. -- ends switch and subcommand parsing. Every following value is positional even when it begins with -.

example input.txt --verbose --count=2 output.txt
example -- --name-starting-with-dashes

Parse Errors

Invalid command lines throw parse_error. Unknown commands and switch errors are thrown by command::parse(). Missing required options or commands and missing, unexpected, or invalid positional parameters are thrown when validation is first triggered. A missing required option is reported as Missing option --email <EMAIL>.

Catch the exception at the application boundary to produce a concise command-line error and nonzero exit code.

#include <iostream>
#include <kaycxx/cli.hpp>
using namespace kaycxx::cli;
int main(int argc, char* argv[]) {
auto example = app{"example"};
auto input = example.parameter<std::string>("INPUT", "Input file");
try {
auto arguments = example.parse(argc, argv);
return 0;
} catch (parse_error const& error) {
std::cerr << example.name() << ": " << error.what() << '\n';
return 1;
}
}
Defines and parses a command-line application.
Definition app.hpp:50
Handle for a registered option.
Definition option_handle.hpp:25
Error thrown when command line arguments cannot be parsed.
Definition parse_error.hpp:19
Provides the umbrella include for the kaycxx CLI library.