DEV Community

Hendrik
Hendrik

Posted on

Lyra : Command Line Parser for C++

Parsing conmmand line arguments is a tedious task and many programming languages have libraries for it. While researching such libraries for C++
I found Lyra which works as a header-only library for C++11 and higher.

It supports the usual positional and optional arguments known from POSIX style command line tools and has the possibility to automatically generate a help text.

For a full set of examples see the documentation.

Example: Optional Arguments and Help Text

#include <iostream>
#include <lyra/lyra.hpp>

int main(int argc, const char** argv)
{
    // Variables to put arguments into:
    int width = 0;
    int height = 0;
    bool show_help = false;

    const auto cli = lyra::help(show_help)
        | lyra::opt(width, "width")
        ["-w"]["--width"]("How wide should it be?")
        | lyra::opt(height, "height")
        ["-x"]["--height"]("How high should it be?");


    // Parse the program arguments:
    const auto result = cli.parse({ argc, argv });

    if (!result)
    {
        std::cerr << result.errorMessage() << std::endl;
        std::cerr << cli;
        exit(1);
    }

    if(show_help)
    {
        std::cout << cli << '\n';
        exit(0);
    }

    std::cout << "width * height: " << width * height << '\n';
}

Starting the programm without arguments yields the default values, using -h triggers the help text:

./a.out 
width * height: 0
./a.out -w 15 -x 10
width * height: 150
./a.out -h
Usage:
  a.out [-?|-h|--help] [-w|--width] [-x|--height]

Options, arguments:
  -?, -h, --help

  Display usage information.

  -w, --width <width>

  How wide should it be?

  -x, --height <height>

  How high should it be?

Entering wrong arguments also leads to the help text being printed

./a.out --blabla dddd
Unrecognized token: --blabla
Usage:
  a.out [-?|-h|--help] [-w|--width] [-x|--height]

Options, arguments:
  -?, -h, --help

  Display usage information.

  -w, --width <width>

  How wide should it be?

  -x, --height <height>

  How high should it be?

Non-optional Arguments

Non-optional parameters can be specified by using lyra::arg instead of lyra::opt. Non-optional arguments are just specified by their position in the CLI.

const auto cli = lyra::help(show_help)
        | lyra::arg(width, "width")("How wide?")
        | lyra::arg(height, "height")("How high should it be?");
./a.out
width * height: 0
./a.out 10 10
width * height: 100

Top comments (0)