Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
A

args

> 开发工具
Open source

A header-only C++ argument parser library. Supposed to be flexible and powerful, and attempts to be compatible with the functionality of the Python standard a

1.6K stars0 likes3 views
WebsiteGitHub

About

A header-only C++ argument parser library. Supposed to be flexible and powerful, and attempts to be compatible with the functionality of the Python standard a

args

This library is considered feature-complete by its creator. It will still receive bug fixes, and good pull requests will be accepted, but no new major functionality or API changes will be added to this codebase. A simple, small, flexible, single-header C++11 argument parsing library.

This is designed to appear somewhat similar to Python's argparse, but in C++, with static type checking, and hopefully a lot faster (also allowing fully nestable group logic, where Python's argparse does not).

UTF-8 support is limited at best. No normalization is performed, so non-ascii characters are very best kept out of flags, and combined glyphs are probably going to mess up help output if you use them. Most UTF-8 necessary for internationalization should work for most cases, though heavily combinatory UTF alphabets may wreak havoc.

This program is MIT-licensed, so you can use the header as-is with no restrictions. I'd appreciate attribution in a README, Man page, or something if you are feeling generous, but all that's required is that you don't remove the license and my name from the header of the args.hxx file in source redistributions (ie. don't pretend that you wrote it). I do welcome additions and updates wherever you feel like contributing code.

The API documentation can be found at https://taywee.github.io/args

The code can be downloaded at https://github.com/Taywee/args

There are also somewhat extensive examples below.

You can find all the test cases in https://github.com/Taywee/args/tree/master/test. Each test is a small self-contained .cxx file with its own main(), so they double as focused usage examples.

What does it do?

It:

  • Lets you handle flags, flag+value, and positional arguments simply and elegantly, with the full help of static typechecking.
  • Allows you to use your own types in a pretty simple way.
  • Lets you use count flags, and lists of all argument-accepting types.
  • Allows full validation of groups of required arguments, though output isn't pretty when something fails group validation. User validation functions are accepted. Groups are fully nestable.
  • Generates pretty help for you, with some good tweakable parameters.
  • Lets you customize all prefixes and most separators, allowing you to create an infinite number of different argument syntaxes.
  • Lets you parse, by default, any type that has a stream extractor operator for it. If this doesn't work for your uses, you can supply a function and parse the string yourself if you like.
  • Lets you decide not to allow separate-argument value flags or joined ones (like disallowing --foo bar, requiring --foo=bar, or the inverse, or the same for short options).
  • Allows you to create subparsers, to reuse arguments for multiple commands and to refactor your command's logic to a function or lambda.
  • Allows one value flag to take a specific number of values (like --foo first second, where --foo slurps both arguments).
  • Allows you to have value flags only optionally accept values.
  • Provides autocompletion for bash.

What does it not do?

There are tons of things this library does not do!

It will not ever:

  • Allow you to intermix multiple different prefix types (eg. ++foo and --foo in the same parser), though shortopt and longopt prefixes can be different.
  • Allow you to make flags sensitive to order (like gnu find), or make them sensitive to relative ordering with positionals. The only orderings that are order-sensitive are:
    • Positionals relative to one-another
    • List positionals or flag values to each of their own respective items
  • Allow you to use a positional list before any other positionals (the last argument list will slurp all subsequent positional arguments). The logic for allowing this would be a lot more code than I'd like, and would make static checking much more difficult, requiring us to sort std::string arguments and pair them to positional arguments before assigning them, rather than what we currently do, which is assigning them as we go for better simplicity and speed. The library doesn't stop you from trying, but the first positional list will slurp in all following positionals

How do I install it?

bash
sudo make install

Or, to install it somewhere special (default is /usr/local):

bash
sudo make install DESTDIR=/opt/mydir

You can also copy the file into your source tree, if you want to be absolutely sure you keep a stable API between projects.

If you prefer other installation methods, many standard ones are available and included, including CMake, conan, buck, and meson. An example CMake file using args is included in the examples directory.

I also want man pages.

bash
make doc/man
sudo make installman

This requires Doxygen

I want the doxygen documentation locally

bash
doxygen Doxyfile

Your docs are now in doc/html

How to depend on it using tipi.build?

Simply add the following entry to your .tipi/deps file

json
{
    "taywee/args": { "@": "6.4.1" }
}

You can optionally remove the @ section to target HEAD easily.

How do I use it?

Create an ArgumentParser, modify its attributes to fit your needs, add arguments through regular argument objects (or create your own), and match them with an args::Matcher object (check its construction details in the doxygen documentation.

Then you can either call it with args::ArgumentParser::ParseCLI for the full command line with program name, or args::ArgumentParser::ParseArgs with just the arguments to be parsed. The argument and group variables can then be interpreted as a boolean to see if they've been matched.

All variables can be pulled (including the boolean match status for regular args::Flag variables) with args::get.

Group validation is weird. How do I get more helpful output for failed validation?

This is unfortunately not possible, given the power of the groups available. For instance, if you have a group validation that works like (A && B) || (C && (D XOR E)), how is this library going to be able to determine what exactly when wrong when it fails? It only knows that the entire expression evaluated false, not specifically what the user did wrong (and this is doubled over by the fact that validation operations are ordinary functions without any special meaning to the library). As you are the only one who understands the logic of your program, if you want useful group messages, you have to catch the ValidationError as a special case and check your own groups and spit out messages accordingly.

Is it developed with regression tests?

Yes. The test/ directory contains the regression suite, with each test compiled into its own executable and run via CMake's ctest. Tests run on every push and pull request via GitHub Actions, covering Linux, macOS, and Windows in both Debug and Release builds.

To run them locally:

bash
cmake -B build
cmake --build build
ctest --test-dir build --output-on-failure

Or via the Makefile wrapper:

bash
make runtests

The tests don't depend on any third-party framework — test/test_helpers.hxx provides a handful of inline assertion helpers (test::require, test::require_throws_as, etc.) and that's it. To debug a single failure, just run the corresponding executable directly, e.g. ./build/argstest-help_flag.

Examples

All the code examples here will be complete code examples, with some output.

Simple example:

…
bash
 % ./test
 % ./test -h
  ./test {OPTIONS} 

    This is a test program. 

  OPTIONS:

      -h, --help         Display this help menu 

    This goes after the options. 
 % 

Boolean flags, special group types, different matcher construction:

…
…

Argument flags, Positional arguments, lists

…
…

Commands

…
bash
% ./test -h
  ./test COMMAND [paths...] {OPTIONS}

    git-like parser

  OPTIONS:

      commands
        add                               add file contents to the index
        commit                            record changes to the repository
      arguments
        --git-dir=[path]
        -h, --help                        help
        paths...                          files
      "--" can be used to terminate flag options and force all following
      arguments to be treated as positional options

% ./test add 1 2
Add 1 2

Refactoring commands

…
…

Custom type parsers (here we use std::tuple)

…
…

As you can see, with your own types, validation can get a little weird. Make sure to check and throw a parsing error (or whatever error you want to catch) if you can't fully deduce your type. The built-in validator will only throw if there are unextracted characters left in the stream.

Long descriptions and proper wrapping and listing

…
…

Completion

Completion currently only supports bash.

…
bash
g++ -ocompletiontest ./completiontest.cxx "-I$args_path"
PATH="$PWD:$PATH"
_args() {
    _init_completion -n 2> /dev/null
    local program comparg

    program="${COMP_WORDS[0]}"
    comparg="--complete" # replace this with your flag

    COMPREPLY=($("$program" "$comparg" bash "$COMP_CWORD" "${COMP_WORDS[@]}" 2> /dev/null))
    [[ $COMPREPLY ]] && return
    _filedir
}
complete -F _args completiontest

# Now when you type `completiontest --` and press tab, you'll get completion

Customizing parser prefixes

dd-style

…
bash
 % ./test help
  ./test {OPTIONS}

    This command likes to break your disks

  OPTIONS:

      help                              Show this help menu.
      bs=[BYTES]                        Block size
      skip=[BYTES]                      Bytes to skip
      if=[BLOCK SIZE]                   Block size
      of=[BLOCK SIZE]                   Block size

 % ./test bs=1024 skip=7 if=/tmp/input
bs = 1024
skip = 7
if = /tmp/input

Windows style

The code is the same as above, but the two lines are replaced out:

cpp
parser.LongPrefix("/");
parser.LongSeparator(":");
bash
 % ./test /help     
  ./test {OPTIONS}

    This command likes to break your disks

  OPTIONS:

      /help                             Show this help menu.
      /bs:[BYTES]                       Block size
      /skip:[BYTES]                     Bytes to skip
      /if:[BLOCK SIZE]                  Block size
      /of:[BLOCK SIZE]                  Block size

 % ./test /bs:72 /skip:87 /if:/tmp/test.txt
bs = 72
skip = 87
if = /tmp/test.txt
 % 

Group nesting help menu text

…
…

Mapping arguments

I haven't written out a long example for this, but here's the test case you should be able to discern the meaning from:

…

How fast is it?

This should not really be a question you ask when you are looking for an argument-parsing library, but every test I've done shows args as being about 65% faster than TCLAP and 220% faster than boost::program_options.

The simplest benchmark I threw together is the following one, which parses the command line -i 7 -c a 2.7 --char b 8.4 -c c 8.8 --char d with a parser that parses -i as an int, -c as a list of chars, and the positional parameters as a list of doubles (the command line was originally much more complex, but TCLAP's limitations made me trim it down so I could use a common command line across all libraries. I also have to copy in the arguments list with every run, because TCLAP permutes its argument list as it runs (and comparison would have been unfair without comparing all about equally), but that surprisingly didn't affect much. Also tested is pulling the arguments out, but that was fast compared to parsing, as would be expected.

The run:

bash
% g++ -obench bench.cxx -O2 -std=c++11 -lboost_program_options
% ./bench
args seconds to run: 0.895472
tclap seconds to run: 1.45001

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

C++argsargument-parserargument-parsingcli

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category开发工具
PricingOpen source

> Related tools

V
VS Code
流行的开源代码编辑器
G
Git
分布式版本控制系统
V
Vite
下一代前端构建工具