Skip to content

A small library to parse command line arguments in C++

License

Notifications You must be signed in to change notification settings

tcalmant/cpp-mini-argparse

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

cpp-mini-argparse

A small library to parse command line arguments in C++, without external dependencies besides the standard library.

This was made in a hurry for a specific project, to avoid license issues.

It supports:

  • Flag and store (one value) arguments
  • A short and a long alias for an argument
  • A basic usage print

It requires:

  • A C++11 compiler
  • The C++ standard library (iostream, list, map and string)

Note: This is not a production-ready library, but it can be useful for some developments.

Sample usage

This snippet can be found in the sample folder.

#include <iostream>
#include "argparse/argparse.hpp"

using namespace argparse;
using namespace std;

int main(const int argc, const char **argv)
{
    try
    {
        auto parser = ArgumentParser("FooBar");
        parser.add_argument("help", "-h", "--help", "Displays the help message");
        parser.add_argument("conf", "-c", "--conf", "Path to a file", STORE);
        parser.add_argument("force", "-f", "", "Force hello world", FLAG);

        if (!parser.parse(argv, argc))
        {
            cout << "Error parsing arguments" << endl;
            return 1;
        }
        else if (parser.get("help").is_set())
        {
            parser.print_usage();
            return 0;
        }

        auto conf_arg = parser.get("conf");
        if (conf_arg.is_set())
        {
            cout << "Conf file: " << conf_arg.get_value() << endl;
        }
        else
        {
            cout << "No configuration given." << endl;
        }

        if(parser.get("force").is_set())
        {
            cout << "HELLO WORLD" << endl;
        }
    }
    catch (const char *error)
    {
        cerr << "ERROR: " << error << endl;
        return 1;
    }
    catch (std::string &error)
    {
        cerr << "ERROR: " << error << endl;
        return 1;
    }

    return 0;
}

Build samples

The samples can be compiled using CMake (3.5+):

  1. Create the cache directory: mkdir build
  2. Move inside it cd build
  3. Prepare the build environment: cmake ..
  4. Build the project: cmake --build .
  5. Run a sample: ./basic-sample -h or ./Debug/basic-sample -h according to the CMake version and OS.

About

A small library to parse command line arguments in C++

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published