Simple API
This is the first example to open when you want the default cli20 flow. It shows the smallest useful cli20 program: one flag, one optional named argument, and one required positional input.
Source
Source: examples/simple_api.cc
examples/simple_api.cc
#include <iostream>
#include "cli/argument.hh"
#include "cli/parser.hh"
struct Args {
cli::Description description{
"Minimal cli20 program with one flag, one option, and one positional."};
cli::Help<> help;
cli::Flag<"verbose", 'v'> verbose{{.help = "Enable verbose logging"}};
cli::StringOption<"output", 'o'> output{{.help = "Optional output file"}};
cli::Positional<std::string> input{
{.help = "Input file", .presence = cli::required}};
};
auto main(int argc, char* argv[]) -> int {
const auto args = cli::parse_or_exit<Args>(argc, argv);
if (args.verbose.value()) {
std::cout << "verbose: true\n";
}
if (args.output) {
std::cout << "output: " << *args.output << '\n';
}
std::cout << "input: " << *args.input << '\n';
return 0;
}
What This Example Shows
This example declares a CLI as ordinary typed fields, mixes a flag with an
optional named value and a required positional, and lets cli20 handle standard
help and error flow. On success, verbose becomes a bool, output holds an
optional path-like string, and input holds the required file name.
Try It
cli20@cli20-dev:~$ simple_api
Things to try:
- Happy path —
--verbose --output result.txt input.cc - No flag —
input.cc(just the required positional) - Help —
--help - Missing positional —
--verboseto see the required-argument error