r/cpp • u/Adept-Restaurant-541 • May 06 '26
Are you satisfied with the current state of C++ CLI parsers?
There are already many excellent C++ CLI parsers out there, but most of them still revolve around mutable runtime builder APIs.
Most existing parsers look something like this:
CLI::App app{"example"};
std::string output;
bool verbose = false;
std::vector<std::string> inputs;
app.add_option("-o,--output", output, "output file");
app.add_flag("-v,--verbose", verbose, "verbose mode");
app.add_option("inputs", inputs, "input files")->required();
CLI11_PARSE(app, argc, argv);
Why are duplicate option names still runtime errors in C++ CLI parsers? Where is the compile-time validation?
Why is the command schema still built through runtime mutation? Many CLI schemas are effectively static. Why not treat them as a static schema and let the compiler enforce it?
One of the things I love about C++ is its ability to express intent and constraints in the type system and let the compiler enforce them.
But many C++ CLI parsers still rely heavily on runtime mutation and stringly-typed APIs.
Rust has clap, which is a great typed CLI parser. So what about C++?
So I wanted to explore what that direction could look like in modern C++20.
I built a new C++ CLI parser that takes a different approach:
#include <cli/cli.hh>
struct Args {
cli::Flag<"verbose", 'v'> verbose;
cli::StringOption<"output", 'o'> output;
cli::Positional<std::string, cli::nargs::one_or_more> inputs;
};
using namespace std;
auto main(int argc, char** argv) -> int {
// Returns parsed Args or exits with an error message.
const auto args = cli::parseOrExit<Args>(argc, argv);
std::cout << "verbose: " << args.verbose.value() << '\n';
if (args.output.has_value()) {
std::cout << "output: " << *args.output.value() << '\n';
}
for (const auto& input : args.inputs.value()) {
std::cout << input << '\n';
}
}
Try this out on Godbolt: https://godbolt.org/z/53d8rEMoP
The goal is to explore a C++20-native parser API where the command line is represented as a typed schema rather than a mutable runtime builder.
The interesting part for me is that this works in plain C++20, without reflection, macros, code generation, or external tooling.
Repository: https://github.com/CLI20-dev/cli20
Still early-stage. I'm mainly looking for feedback on API ergonomics, diagnostics, and the compile-time/runtime tradeoff.
35
u/G6L20 May 06 '26
Since c++26 reflection is available I use my own annotation based library. Here is a git-like cli used within test: https://github.com/Garcia6l20/reflex/blob/main/cli/tests/include/git.hpp
6
u/ksergey May 06 '26
cxxopts old time user
4
u/arihoenig May 06 '26
I use cxxopt works perfectly fine. With reflection I am expecting to create my own header library for arg parsing
4
u/fdwr fdwr@github π May 07 '26
Most argument parsers have never really satisfied my needs, especially when it comes to more complex things like passing a list of numbers (e.g.
dimensions:[640,480,3]) or passing a dictionary of values (inputs:{fileA.png fileB.png} outputs:{combined.dat}, and so I've written my own. Most of the time, I'd like the argument parser to just fill in some struct for me rather than writing a bunch of querying code myself per app. Also, like you realized, schemas don't really need to be dynamic, and so rather than use a builder, I just tended to declare schemas as definition structs.1
u/holyblackcat May 07 '26
The first thing I checked for is does this correctly handle unicode arguments on Windows? It doesn't seem to.
I did something similar before (but with macro-based reflection), but I now think that it doesn't have much benefit over a simple 100-line implementation (with runtime error reporting).
It's sure cool to be able to do this with reflection (I assume this uses a boost-pfr-like approach?), but the actual usability improvement is minimal. Big real-world programs are going to want to register the options independently from different TUs (to avoid having to recompile everything when adding one option), and this brings you back to square one to runtime reporting of duplicate options.
3
u/KyoshiYoshi May 07 '26
At a first glance this seems like exactly what I need. Iβm looking to upgrade my cli parser from cli11 to something more modern, and your design philosophy almost perfectly aligns with what Iβm looking for. Iβll take a deeper look in the near future. good stuff!
3
u/arthurno1 May 07 '26 edited May 07 '26
I don't like any of them :). As much as I like C++ and C, I am a big fan of codegenerators and automation.
I always thought there should be an automated way to generate all this options parsing, so I wrote a small codegenerator in Emacs Lisp for myself where I can type options in a text file, process the file with Lisp and dump C++ file out of it. I have a template for options parser and main function, and it generates a file where I only have to implement the program logic:
In the example of basename (a re-implementation of the one from core-utils), basename.en is a option/help specification, as close to a simple text file as possible, including text formatting. Looks something like this:
Since it is a text file, I can just take the entire text formatting out of my "spec" file, and emit formatted text to C++ file, so I don't have to do formatting via embeded escapes (\t\n etc) in strings.
Include template (incl-template.hh) for options parser looks like this (just for the illustration):
It generates me code like this (basename.hh):
As illustration part of the code in basename.cc (entirely autogenerated):
All the source code for help, usage, options parsing and even main are generated from the Lisp code generator and template files. What I have to do in C++ is just implement the logic for the program itself in basename-impl.cc:
A run (there is a typo in the help file :-)):
I took the basename program here as an example since it is so small, but I can use it for any CLI program, I just need to provide program.en spec, but I am not writing much in C++ nowadays anyway, so I am not really using it and the options spec is not very advanced.
The problem is, of course, it mandates use Emacs, which is probably not for everyone, and not for general public, but since I am using Emacs to code with it, and hacking it often myself, for me it is natural to use the same tool for writing shell scripts, code gens and other automation like this.
12
u/MFHava WG21|π¦πΉ NB|P3049|P3625|P3729|P3786|P3813|P4216 May 06 '26
Gotta be honest: I canβt remember the last time I wrote a
mainβ¦So whilst I applaud the goal of coming up with a more modern way to do
argv-parsing, Iβm perfectly satisfied with whatever we have currently in place.2
u/gosh May 07 '26
I created my own because what I found was too weak
docs
code
2
u/Ateist May 07 '26
You missed a few very important things:
a) the variables you initialize in CLI have default values
b) the variables you want to initialize in CLI can be all over your program - not only in your "main.cpp"
c) the variables can load that default value from external configuration file
d) the variables might want to save their current value to external configuration file
e) ideally, there should be as little duplication as possible.
So a proper CLI/Settings interface would be done via C++26 Reflection/Singleton register where all you have to write to add individual configuration value is something like this:
while everything else is automatically generated.
1
u/willi_kappler May 07 '26
Nice library, I like the new and fresh approach. Can you please add a license file ?
Just recently this was posted:
https://www.reddit.com/r/cpp/comments/1sv4w78/using_reflection_for_parsing_command_line/
But that requires C++26, I'm happy to see that your library also supports an older C++ version.
Will give it a try when I have more time.
1
u/chibuku_chauya May 07 '26
I want an argument parser that accepts the same style of options as GCC and Clang do but nothing Iβve ever come across can do it.
1
u/wrosecrans graphics and network things May 09 '26
I am a huge fan of Docopt. Basically, you write your help text in a precise format, and that help text string is parsed as a DSL to define all your options, and you pull the results from that.
Super convenient. No duplication of constructing the parser and writing the doctring. And there are implementations for many programming languages, so you can learn the API once and have consistency between C++ and Python, or whatever languages you use.
1
u/elder_george May 07 '26
Here, I'm saying it: There are too many CLI parsers for C++ in the vcpkg repo alone.
It's almost like dozens of programmers had started with ideas of a program, wrote
argvparsing code, and got so distracted by polishing it that they never finished the actual program. Unfortunately, this is all too common with our beloved language in general, mostly because "the batteries" are so much not included.-1
u/BigReception26 May 06 '26
No
-5
u/official_business May 06 '26
XKCD 927.
And here's me using getopt_long.
8
u/[deleted] May 06 '26
[removed] β view removed comment