ArgvParser - C++ class for convenient parsing of command line options

ArgvParser is a single C++ class that eases handling of command line options and arguments.

Features

  • Handling of POSIX style short options (-h) and GNU style long options (–help).
  • Options can be defined as required and the parser issues an error if any required option is missing. Options can also be to defined to require a value (–help whatever or –help=whatever) and the parser will report if any required option values are missing.
  • One can assign multiple alternative names of a certain option.
  • A special help option (both long and short name) can be set and the parser will report any occurence of the option immediately.
  • The class can automatically generate a help page from the defined set of options. This help page summarizes all options, showing their descriptions and whether they are required or require a value. Additionally the help page can be enhanced with some introductory description and a list of return values. All output is pretty-printed (with proper indentation and line breaks) to fit a certain width (e.g. of a terminal window).

The code is extensively documented and easy to understand. The tarball contains a number of test cases (tests.cpp) that show the usage of the parser.

Example

Here is a simple example that shows how to use the parser:

#include <iostream>;
#include "argvparser.h"

using namespace std;
using namespace CommandLineProcessing;

int main(int argc, char** argv)
{
  ArgvParser cmd;

  // init
  cmd.setIntroductoryDescription("This is foo written by bar.");

  //define error codes
  cmd.addErrorCode(0, "Success");
  cmd.addErrorCode(1, "Error");

  cmd.setHelpOption("h", "help", "Print this help page");

  cmd.defineOption("version", ArgvParser::NoOptionAttribute,
                   "Be verbose");
  cmd.defineOptionAlternative("verbose","v");

  cmd.defineOption("foo", ArgvParser::OptionRequiresValue,
                   "Fooishness. Default value: 0");

  // finally parse and handle return codes (display help etc...)
  int result = cmd.parse(argc, argv);

  if (result != ArgvParser::NoParserError)
  {
    cout << cmd.parseErrorDescription(result);
    exit(1);
  }

  // now query the parsing results
  if (cmd.foundOption("foo"))
  {
    string = cmd.optionValue("foo");

    ...
  }

  ...
}

License

This code is licensed under the GNU Public License (GPL).

Alternatives

There are a lot of C++ command line parsers out there. Two examples are:

Table Of Contents

Previous topic

Multithreaded-OpenGL Rendering mit Picking-Fähigkeit mit Qt

Next topic

Simple Video Overlays with VLC and Python

NeuroDebian

LinkedIn

Ohloh profile for Michael Hanke

Not f'd — you won't find me on Facebook