|
CPP-AP 3.0.1
Command-line argument parser for C++20
|
Important:
This tutorial covers the most common use cases and features of the library. For more in-depth information and advanced usage, please refer to the full documentation. Instructions for building the documentation are available in the Dev Notes page.
For CMake projects you can simply fetch the library in your CMakeLists.txt file:
To use the CPP-AP in a Bazel project add the following in the MODULE.bazel (or WORKSPACE.bazel) file:
Important: CPP-AP versions older than 2.5.0 do not support building with Bazel.
And then add the "@cpp-ap//:cpp-ap" dependency for the target you want to use CPP-AP for by adding it to the deps list. For instance:
If you do not use CMake, you can download the desired library release, extract it in a desired directory and simply add <cpp-ap-dir>/include to the include directories of your project.
To use the argument parser in your code you need to use the ap::argument_parser class.
Important:
When creating an argument parser instance, you must provide a program name to the constructor.
The program name given to the parser cannot be empty and must not contain whitespace characters.
- Additional parameters you can specify for a parser instance include:
- The program's version and description - used in the parser's configuration output (
std::cout << parser).- Verbosity mode -
falseby default; if set totruethe parser's configuration output will include more detailed info about arguments' parameters in addition to their names and help messages.- Arguments - specify the values/options accepted by the program.
- Argument Groups - organize related optional arguments into sections and optionally enforce usage rules.
- The unknown argument flags handling policy.
Tip:
You can specify the program version using a string (like in the example above) or using the
ap::versionstructure:parser.program_version({0u, 0u, 0u})parser.program_version({ .major = 1u, .minor = 1u, .patch = 1u });ap::version ver{2u, 2u, 2u};parser.program_version(ver);NOTE: The
ap::versionstruct
- contains the three members -
major,minor,patch- all of which are of typestd::uint32_t,- defines a
std::string str() constmethod which returns av{major}.{minor}.{path}version string,- defines the
std::ostream& operator<<for stream insertion.
The parser supports positional and optional arguments.
Note:
The general rules for parsing arguments are described in the Parsing arguments section.
To add an argument, use:
For optional arguments, you may also specify a secondary (short) name:
or use only the secondary name:
Important: An argument's value type must be
ap::none_typeor satisfy all of the following requirements:
- Constructible from
const std::string&or overloadstd::istream& operator>>.
- The parser will always try direct initialization from std::string first, and only fall back to the extraction operator if direct initialization fails.
- Satisfy the
std::semiregularconcept (default-initializable and copyable).
Note:
- The default value type of any argument is
std::string.- If the argument's value type is
ap::none_type, the argument will not accept any values and therefore no value-related parameters can be set for such argument. This includes:
Flags are essentially optional arguments with a boolean value type.
By default, flags store true when parsed from the command-line. You can invert this behavior:
Parameters which can be specified for both positional and optional arguments include:
help - The argument's description which will be printed when printing the parser class instance.
hidden - If this option is set for an argument, then it will not be included in the program description.By default all arguments are visible, but this can be modified using the hidden(bool) setter as follows:
required - If this option is set for an argument and it's value is not passed in the command-line, an exception will be thrown. Important:
- By default positional arguments are set to be required, while optional arguments have this option disabled by default.
- The default value of the value parameter of the
required(bool)function istruefor both positional and optional arguments.
Warning:
- If a positional argument is defined as non-required, then no required positional argument can be defined after (only other non-required positional arguments and optional arguments will be allowed).
- If an argument is suppressing (see suppress arg checks and Suppressing Argument Group Checks), then it cannot be required (an exception will be thrown).
suppress_arg_checks - Using a suppressing argument results in suppressing requirement checks for other arguments.If an argument is defined with the suppress_arg_checks option enabled and such argument is explicitly used in the command-line, then requirement validation will be suppressed/skipped for other arguments. This includes validating whether:
Note:
- All arguments have the
suppress_arg_checksoption disabled by default.- The default value of the value parameter of the
argument::suppress_arg_checks(bool)method istruefor all arguments.
Warning:
- Enabling the
suppress_arg_checksoption has no effect on argument group requirements validation.- Enabling argument checks suppressing is not possible for required arguments (an exception will be thrown).
nargs - Sets the allowed number of values to be parsed for an argument.The nargs parameter can be set as:
Specific number:
Fully bound range:
Partially bound range:
Unbound range:
Important:
The default
nargsparameter value is:
ap::nargs::range(1ull)for positional argumentsap::nargs::any()for optional arguments
greedy - If this option is set, the argument will consume ALL command-line values until it's upper nargs bound is reached. Note:
- By default the
greedyoption is disabled for all arguments.- The default value of the parameter of the
argument::greedy(bool)method is true for all arguments.
Tip:
- Enabling the
greedyoption for an argument only makes sense for arguments with string-like value types.- If no explicit
nargsbound is set for a greedy argument, once parsing of such argument begins, it will consume all remaining command-line arguments.
Consider a simple example:
Here the program execution should look something like this:
Notice that even though the -v and --type command-line arguments have flag prefixes and are not defined by the program, they are not treated as unknown arguments (and therefore no exception is thrown) because the --args argument is marked as greedy and it consumes these command-line arguments as its values.
choices - A list of valid argument values. Important:
- The
choicesfunction can be used only if the argument'svalue_typeis equality comparable (defines the==operator)- The
choicesfunction can be called with:
- A variadic number of values convertible to the argument's value type
- An arbitrary
std::ranges::rangetype with a value type convertible to the argument's value type
Actions are represented as functions, which take the argument's value as an argument. The available action types are:
observe actions | void(const value_type&) - applied to the parsed value. No value is returned - this action type is used to perform some logic on the parsed value without modifying it.
transform actions | value_type(const value_type&) - applied to the parsed value. The returned value will be used to initialize the argument's value.
modify actions | void(value_type&) - applied to the initialized value of an argument.
Tip:
A single argument can have multiple value actions. Instead of writing complex logic in one action, consider composing several simple, focused actions for better readability and reusability.
default_values - A list of values which will be used if no values for an argument have been parsed Warning:
For both positional and optional arguments, setting the
default_valuesparameter disables therequiredoption.
Note:
The
default_valuesfunction can be called with:
- A variadic number of values convertible to the argument's value type
- An arbitrary
std::ranges::rangetype with a value type convertible to the argument's value type
Apart from the common parameters listed above, for optional arguments you can also specify the following parameters:
Here the print_debug_info function will be called right after parsing the --debug-info flag and the program will exit, even if there are more arguments after this flag.
implicit_values - A list of values which will be set for an argument if only its flag but no values are parsed from the command-line. Note:
The
implicit_valuesfunction can be called with:
- A variadic number of values convertible to the argument's value type
- An arbitrary
std::ranges::rangetype with a value type convertible to the argument's value type
Tip:
The
implicit_valuesparameter is extremely useful when combined with default value (e.g. in case of boolean flags - see Adding Arguments).
print_help | on-flag
Prints the parser's help message to the output stream and optionally exits with the given code.
check_file_exists | observe (value type: std::string)
Throws if the provided file path does not exist.
gt | observe (value type: arithmetic)
Validates that the value is strictly greater than lower_bound.
geq | observe (value type: arithmetic)
Validates that the value is greater than or equal to lower_bound.
lt | observe (value type: arithmetic)
Validates that the value is strictly less than upper_bound.
leq | observe (value type: arithmetic)
Validates that the value is less than or equal to upper_bound.
within | observe (value type: arithmetic)
Checks if the value is within the given interval. Bound inclusivity is customizable using template parameters.
The CPP-AP library defines several default arguments, which can be added to the parser's configuration as follows.
Note:
The
default_argumentsfunction can be called with:
- A variadic number of
ap::default_argumentvalues- An arbitrary
std::ranges::rangetype with theap::default_argumentvalue type
p_input:
p_output:
o_help:
o_version:
o_input and o_multi_input:
o_output and o_multi_output:
Argument groups provide a way to organize related arguments into logical sections and enforce group-wise requirements.
By default, every parser comes with two predefined groups:
add_positional_argument.add_optional_argument or add_flag without explicitly specifying an argument group. Note:
All predefined arguments are bound to one of the predefined groups.
A new group can be created by calling the add_group method of an argument parser:
The group’s name will appear as a dedicated section in the help message and arguments added to this group will be listed under Output Options instead of the default Optional Arguments section.
Note:
If a group has no visible arguments, it will not be included in the parser's help message output at all.
Arguments are added to a group by passing the group reference as the first parameter to the add_optional_argument and add_flag functions:
User-defined groups can be configured with special attributes that change how the parser enforces their usage:
required() – at least one argument from the group must be provided by the user, otherwise parsing will fail.mutually_exclusive() – at most one argument from the group can be provided; using more than one at the same time results in an error.Both attributes are off by default, and they can be combined (e.g., a group can require that exactly one argument is chosen).
Important:
If a group is defined as mutually exclusive and an argument from this group is used, then the
requiredandnargsattribute requirements of other arguments from the group will NOT be verified.Consider the example in the section below. Normally the
--output, -oargument would expect a value to be given in the command-line. However, if the--print, -pflag is used, then thenargsrequirement of the--output, -oargument will not be verified, and therefore no exception will be thrown, even though thenargsrequirement is not satisfied.
Below is a small program that demonstrates how to use a mutually exclusive group of required arguments:
When invoked with the --help flag, the above program produces a help message that clearly shows the group and its rules:
Similarly to suppressing argument checks, an argument can suppress the requirement checks of argument groups:
If such argument is used, the requirement checks associated with the group attributes will not be validated.
Note:
- All arguments have the
suppress_group_checksoption disabled by default.- The default value of the value parameter of the
argument::suppress_group_checks(bool)method istruefor all arguments.
Warning:
- Enabling the
suppress_group_checksoption has no effect on argument requirements validation.- Enabling argument group checks suppressing is not possible for required arguments (an exception will be thrown).
To parse the command-line arguments use the void argument_parser::parse_args(const AR& argv) method, where AR must be a type that satisfies the std::ranges::forward_range concept and its value type is convertible to std::string.
The argument_parser class also defines the void parse_args(int argc, char* argv[]) overload, which works directly with the argc and argv arguments of the main function.
Important:
The
parse_args(argc, argv)method ignores the first argument (the program name) and is equivalent to calling:parse_args(std::span(argv + 1, argc - 1));
Tip:
The
parse_argsfunction may throw anap::argument_parser_exceptionif the configuration of the defined arguments is invalid or the parsed command-line arguments do not match the expected configuration. To simplify error handling, theargument_parserclass provides atry_parse_argsmethod which will automatically catch these exceptions, print the error message as well as the help message of the deepest used parser (see Subparsers), and exit with a failure status.Internally, This is equivalent to:
try {parser.parse_args(...);}std::cerr << "[ap::error] " << err.what() << std::endl << parser.resolved_parser() << std::endl;std::exit(EXIT_FAILURE);}Base type for the argument parser functionality errors/exceptions.Definition exceptions.hpp:18
The simple example below demonstrates how (in terms of the program's structure) the argument parsing should look like.
An optional argument is recognized only when its primary or secondary flag appears in the command-line input. For example:
Here, the argument is parsed only if either --optional (primary flag) or -o (secondary flag) is present. If neither flag is given, the argument is ignored.
Important:
The parser will try to assign the values following such flag to the specified argument until:
- A different argument flag is encountered:
// program.cppparser.add_optional_argument("first", "f");parser.add_optional_argument("second", "s");parser.try_parse_args(argc, argv);/* Example execution:<blockquote>‍./program --first value1 value2 --second value3 value4</blockquote>first: value1, value2second: value3, value4
- The upper bound of the argument's nargs parameter is reached:
NOTE: By default an optional argument accepts an arbitrary number of values (the number of values has no upper bound).
parser.add_optional_argument<int>("numbers", "n").nargs(ap::nargs::up_to(3)).help("A list of numbers");<blockquote>‍./program --numbers 1 2 3 4 5</blockquote>[ERROR] : Failed to deduce the argument for values [4, 5]Program: programAn example programOptional arguments:--help, -h : Display the help message--numbers, -n : A list of numbers
Positional arguments are assigned values in the same order they are defined in the program. They are parsed from the command-line input excluding any values that have already been consumed by optional arguments. This means positional arguments no longer need to appear at the beginning of the argument list.
For example:
Important:
- All positional arguments expect at most one value.
- A positional argument's value doesn't have to be preset in the command-line only if the argument is defined as not required.
A positional argument consumes only those values that cannot be assigned to optional arguments. This allows positional arguments to appear after optional arguments in the command-line input.
Tip:
Because optional arguments accept an arbitrary number of arguments by default, it is a good practice to set the nargs parameter for optional arguments (where it makes sense).
A command-line argument beginning with a flag prefix (-- or -) that doesn't match any of the specified optional arguments or a compound of optional arguments (only for short flags) is considered unknown or unrecognized.
By default an argument parser will throw an exception if an unknown argument flag is encountered.
This behavior can be modified using the unknown_arguments_policy method of the argument_parser class, which sets the policy for handling unknown argument flags.
Example:
The available policies are:
ap::unknown_policy::fail (default) - throws an exception if an unknown argument flag is encountered:
ap::unknown_policy::warn - prints a warning message to the standard error stream and continues parsing the remaining arguments:
ap::unknown_policy::ignore - ignores unknown argument flags and continues parsing the remaining arguments:
ap::unknown_policy::as_values - treats unknown argument flags as values:
Important:
- The unknown argument flags handling policy only affects the parser's behaviour when calling the
parse_argsortry_parse_argsmethods.- When parsing known args with
parse_known_argsortry_parse_known_argsall unknown arguments (flags and values) are collected and returned as the parsing result, ignoring the specified policy for handling unknown arguments.Consider a similar example as above with only the argument parsing function changed:
const auto unknown_args = parser.try_parse_known_args(argc, argv);<< "unknown = " << ap::util::join(unknown_args) << std::endl;This would produce the following output regardless of the specified unknown arguments policy.
<blockquote>‍./test --known --unknown</blockquote>known =unknown = --unknown
Compound argument flags are secondary argument flags of which every character matches the secondary name of an optional argument.
Example:
Important:
- If there exists an argument whose secondary name matches a possible compound of other arguments, the parser will still treat the flag as a flag of the single matching argument, not as multiple flags.
- The argument parser will try to assign the values following a compound argument flag to the argument represented by the last character of the compound flag.
If you wish to handle only the specified command-line arguments and leave all unknown/unrecognized arguments, you can use the parse_known_args method.
This method behaves similarly to parse_args() (see Parsing Arguments), however it does not throw an error if unknown arguments are detected. Instead it returnes all the unknown arguments detected during parsing as a std::vector<std::string>.
Consider a simple example:
Here the parser throws exceptions for arguments it doesn't recognize. Now consider the same example with parse_known_args:
Now all the values, that caused an exception for the parse_args example, are collected and returned as the result of argument parsing.
Important:
If a parser encounters an unrecognized argument flag during known args parsing, then the flag will be collected and the currently processed optional argument is reset. That means that any value following an unrecognized flag will be used to parse positional arguments or treated as an unknown argument as well (if there are no unparsed positional arguments). Let's consider an example:
parser.add_positional_argument("positional").help("A positional argument");parser.add_optional_argument("recognized", "r").nargs(ap::nargs::any()).help("A recognized optional argument");const auto unknown_args = parser.parse_known_args(argc, argv);std::cout << "positional = " << parser.value("positional") << std::endl<< "unknown = " << ap::util::join(unknown_args) << std::endl;/* Example execution:<blockquote>‍./program --recognized value1 value2 value3 --unrecognized value4 value5 --recognized value6</blockquote>positional = value4recognized = value1, value2, value3, value6unknown = --unrecognized, value5<blockquote>‍./program value0 --recognized value1 value2 value3 --unrecognized value4 --recognized value5</blockquote>positional = value0recognized = value1, value2, value3, value5unknown = --unrecognized, value4Here
valueis treated either as thepositionalargument's value or as an unknown argument (depending on the input arguments) even though therecognizedoptional argument still accepts values and only after the--recognizedargument flag is encountered the parser continues collecting values for this argument.
Tip:
Similarly to the
parse_argsmethod,parse_known_argshas atryequivalent -try_parse_known_args- which will automatically catch these exceptions, print the error message, and exit with a failure status.
You can retrieve the argument's value(s) with:
value_type{std::forward<U>(fallback_value)} (where U is the deduced type of fallback_value).std::vector<value_type>. Note:
The argument value getter functions might throw an exception if:
- An argument with the given name does not exist
- The argument does not contain any values - parsed or predefined (only getter function
(1))- The specified
value_typedoes not match the value type of the argument
Subparsers allow you to build hierarchical command-line interfaces, where a top-level parser delegates parsing to its subcommands. This is particularly useful for creating CLI applications like git, where commands such as git add, git commit, and git push each have their own arguments.
Each subparser is a separate instance of ap::argument_parser and therefore it can have its own parameters, including a description, arguments, argument groups, subparsers, etc.
For example:
This defines git and git status parsers, each with their own sets of arguments.
You can add as many subparsers as you like, each corresponding to a different command:
All defined subparsers will be included in the parent parser's help message:
When parsing command-line arguments, the parent parser will attempt to match the first command-line token against the name of one of its subparsers.
For example:
Running ap-git submodule init <args> will result in <args> being parsed by the submodule_init parser.
Each parser tracks its state during parsing. The methods described below let you inspect this state:
invoked() -> bool : Returns true if the parser’s name appeared on the command line.
A parser becomes invoked as soon as the parser is selected during parsing, even if parsing is later delegated to one of its subparsers.
finalized() -> bool : Returns true if the parser has processed its own arguments.
This is distinct from invoked(): a parser can be invoked but not finalized if one of its subparsers handled the arguments instead.
resolved_parser() -> ap::argument_parser& : Returns a reference to the deepest invoked parser.
If no subparser was invoked, this simply returns the current parser.
If you run: ./ap-git submodule init, you will get the following state:
The library usage examples and demo projects are included in the cpp-ap-demo submodule. To fetch the submodule content after cloning the main repository, run:
For more detailed information about the demo projects, see the cpp-ap-demo README.
The following table lists the projects provided in the cpp-ap-demo submodule:
| Project | Description |
|---|---|
| Power Calculator | Calculates the value of a $b^e$ expression for the given base and exponents. Demonstrates: The basic usage of positional and optional arguments. |
| File Merger | Merges multiple text files into a single output file. Demonstrates: The usage of default arguments. |
| Numbers Converter | Converts numbers between different bases. Demonstrates: The usage of argument parameters such as nargs, choices, and default values. |
| Verbosity | Prints messages with varying levels of verbosity. Demonstrates: The usage of none_type arguments and compound argument flags. |
| Logging Mode | Logs a message depending on the selected logging mode (quiet, normal, verbose).Demonstrates: The usage of custom argument value types (like enums). |
| Message Logger | Outputs a message to a file, console, or not at all. Demonstrates: The usage of argument groups. |
| AP-GIT | A minimal Git CLI clone with subcommands (init, add, commit, status, push).Demonstrates: The usage of subparsers for multi-command CLIs and complex argument configurations. |
The CPP-AP library provides additional utilities, described on the Utility topic page.