• Stars
    star
    162
  • Rank 231,305 (Top 5 %)
  • Language
    C++
  • License
    MIT License
  • Created over 9 years ago
  • Updated 8 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A simple and lightweight command line parser using C++11.

Simple C++ command line parser

This project supplies a simple, single-header, command-line parser. It is very lightweight and relies on templates. The easiest way is to use it by adding it to your source code. The parser requires C++11 and works fine on gcc (v4.8.2 or later, some earlier versions should work as well), icc (v14 or later), clang and msvc (v18 or later).

Using the parser

Using the parser is straight forward. Only include the header (cmdparser.h) in your application source file, most likely the one that contains the main method. Pass the command line arguments to the parser:

int main(int argc, char** argv) {
	cli::Parser parser(argc, argv);
	/* ... */
}

In the following two sections we'll have a look at setting up the parser and using it.

Setup

Setting up the parser works using the following methods:

  • set_optional<T>(), to include an optional argument
  • set_required<T>(), to include a required argument

The third parameter for creating an optional argument is the default value. This value is used if nothing is provided by the user. Otherwise the optional and required methods are pretty similar:

  1. The shorthand (if the user uses a single slash) string
  2. The longhand (if the user uses two slashes) string
  3. The optional description.

The third parameter is the fourth parameter for optional arguments.

Let's look at an example:

void configure_parser(cli::Parser& parser) {
	parser.set_optional<std::string>("o", "output", "data", "Strings are naturally included.");
	parser.set_optional<int>("n", "number", 8, "Integers in all forms, e.g., unsigned int, long long, ..., are possible. Hexadecimal and Ocatl numbers parsed as well");
	parser.set_optional<cli::NumericalBase<int, 10>>("t", "temp", 0, "integer parsing restricted only to numerical base 10");
	parser.set_optional<double>("b", "beta", 11.0, "Also floating point values are possible.");
	parser.set_optional<bool>("a", "all", false, "Boolean arguments are simply switched when encountered, i.e. false to true if provided.");
	parser.set_required<std::vector<short>>("v", "values", "By using a vector it is possible to receive a multitude of inputs.");
}

Usually it makes sense to pack the Parser's setup in a function. But of course this is not required. The shorthand is not limited to a single character. It could also be the same as the longhand alternative.

Getting values

Getting values is possible via the get method. This is also a template. We need to specify the type of argument. This has to be the same type as defined earlier. It also has to be a valid argument (shorthand) name. At the moment only shorthands are considered here. For instance we could do the following:

//auto will be int
auto number = parser.get<int>("n");

//auto will be int, note specification of numerical base same as when set during parser configuration
auto number = parser.get<cli::NumericalBase<int, 10> >("t");

//auto will be std::string
auto output = parser.get<std::string>("o");

//auto will be bool
auto all = parser.get<bool>("a");

//auto will be std::vector<short>
auto values = parser.get<std::vector<short>>("v");

However, before we can access these values we also need to check if the provided user input was valid. On construction the Parser does not examine the input. The parser waits for setup and a potential call to the run method. The run method runs a boolean value to indicate if the provided command line arguments match the requirements.

What we usually want is something like:

void parse_and_exit(cli::Parser& parser) {
	if (parser.parse() == false) {
		exit(1);
	}
}

Writing this function seems to be redundant. Hence the parser includes it already:

parser.run_and_exit_if_error();

The only difference is that the run_and_exit_if_error method does not provide overloads for passing custom output and error streams. The parse method has overloads to support such scenarios. By default std::cout is used the regular output, e.g., the integrated help. Also std::cerr is used for displaying error messages.

Integrated help

The parser comes with a pre-defined command that has the shorthand -h and the longhand --help. This is the integrated help, which appears if only a single command line argument is given, which happens to be either the shorthand or longhand form.

Finally our main method may look as follows:

int main(int argc, char** argv) {
	cli::Parser parser(argc, argv);
	configure_parser(parser);
	parser.run_and_exit_if_error();
	/* ... */
}

This passes the arguments to the parser, configures the parser and checks for potential errors. In case of any errors the program is exited immediately.

Contributions

This is not a huge project and the file should remain a small, single-header command-line parser, which may be useful for small to medium projects. Nevertheless, if you find any bugs, add small, yet useful, new features or improve the cross-compiler compatibility, then contributions are more than welcome.

License

The application is licensed under the MIT License (MIT).

Copyright (c) 2015 - 2016 Florian Rappl

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

More Repositories

1

Mages

🎩 MAGES is a very simple, yet powerful, expression parser and interpreter.
C#
125
star
2

Mario5TS

The TypeScript version of the Mario5 demo application.
TypeScript
60
star
3

parcel-plugin-externals

Parcel plugin for declaring externals. These externals will not be bundled. 📦
JavaScript
47
star
4

microfrontends-with-blazor-demos

Demos for my talk about "Microfrontends with Blazor". 🚀
HTML
34
star
5

WinFormsX

Windows Forms Extensions Library for the Windows Forms applications / applications using the .NET-Framework.
C#
32
star
6

pwa-example

A short example illustrating some essential steps for creating a progressive web app (PWA).
29
star
7

kras

Efficient server proxying and mocking in Node.js. 💪
TypeScript
27
star
8

react-carousel-hook-example

Example for creating a carousel component based on the useCarousel hook.
TypeScript
27
star
9

react-prerender-demo

A simple demo repository to showcase how to pre-render a React application.
TypeScript
26
star
10

YAMP

Yet Another Math Parser
C#
25
star
11

dets

Generate a single declaration file for your TypeScript project. 🚀
TypeScript
24
star
12

bundler-comparison

Comparison of web resource bundlers. 📦
TypeScript
22
star
13

JsonEditor

Simple example JSON editor powered by a JSON schema. ⛄
C#
16
star
14

portal-sample

Sample React web app to host a portal for (framework independent) mini applications. 🚀
TypeScript
15
star
15

dynamic-esm-microfrontends-demo

Demo for using ESM with dynamic imports for creating microfrontend solutions. 🚀
TypeScript
12
star
16

typescript-fullstack-sample

A sample repository to demonstrate creating a full stack web app using TypeScript with Node.js and React.
TypeScript
11
star
17

parcel-plugin-codegen

Parcel plugin for bundle-time code generation. Simple, powerful, and flexible. 📦
JavaScript
10
star
18

react-arbiter

🚀 Recall all your modules to extend your SPA dynamically at runtime.
TypeScript
9
star
19

jest-fs-snapshot

Jest matcher for filesystem snapshotting.
JavaScript
7
star
20

peerjs-example-app

A small video chat solution using PeerJS as written in the LogRocket article.
TypeScript
7
star
21

tikz.js

Creates standalone graphics based on PGF/TikZ using LaTeX and ImageMagick.
JavaScript
7
star
22

Sumerics

Sumerics is a touch enabled sensor application for doing numerical calculations on Windows 8+ computers.
C#
6
star
23

ts-transform-sample

Sample code for using TypeScript transforms.
TypeScript
6
star
24

piral-webpack-tools

Integrates webpack for debugging and building pilets. 🚀
TypeScript
6
star
25

react-concurrent-mode-example

One example where React concurrent mode excels in user experience. :atom:
JavaScript
5
star
26

ddc-sample-microfrontend-app

A sample microfrontend solution using only Blazor and ASP.NET.
C#
5
star
27

DWX-Trickbox

Demo code as shown in the talk "Another look at the C# (6.0) trickbox" at the DWX 2015.
C#
4
star
28

piral-cli-local-feed

Adds a command to run a local feed service. 🚀
TypeScript
4
star
29

parcel-plugin-import-maps

Enables support for import-maps in Parcel. 🗺️
JavaScript
4
star
30

HarmOsc

The harmonic oscillator on the lattice simulated using the HMC algorithm.
C++
4
star
31

module-federation-with-systemjs-importmap

A simple example showing how a host can dynamically introduce MFs with shared dependencies using Webpack Module Federation.
JavaScript
4
star
32

Partial.Newtonsoft.Json

Helper library to support deserializing fragments of types.
C#
3
star
33

parcel-plugin-browserconfig

A simple plugin for Parcel to traverse a browserconfig.xml file. 📦
JavaScript
3
star
34

piral-nextjs-sample

Migrating an existing Next.js application to be used in a Piral instance as a pilet. 📦
JavaScript
3
star
35

mario5-sample-pilet

A pilet running the Mario5 game for the sample-piral app shell. 👻
TypeScript
3
star
36

DevOpsLittleHelper

Azure Functions demo project for the CodeProject serverless competition.
C#
3
star
37

Piral.Blazor.Server.Samples.Tractor

Repository for the famous tractor micro frontend sample using Piral.Blazor.Server.
C#
3
star
38

volley-sample-pilet

A pilet running the Ultimate Volley game for the sample-piral app shell. 🏐
TypeScript
2
star
39

snow-pilet

A pilet to produce snow on the website
TypeScript
2
star
40

portal-sample-piral

Recreation of my portal-sample project using Piral 🚀.
TypeScript
2
star
41

nightwatch-nunit3-reporter

An NUnit3 reporter for Nightwatch.js. 💻
TypeScript
2
star
42

ts-webpack-virtual-resolve

Example of resolving virtual modules from TypeScript with Webpack.
JavaScript
1
star
43

react-workshop-2022

:atom: Material for the React workshop.
JavaScript
1
star
44

parcel-plugin-at-alias

Parcel plugin to provide support for aliases starting with '@'. 📦
JavaScript
1
star
45

tower-defense-sample-pilet

A pilet running a Tower Defense game for the sample-piral app shell. 🏠
TypeScript
1
star
46

piral-cli-dotenv

Adds a flag to include environment variables from .env files. 🚀
TypeScript
1
star
47

Simplet

A simple C# class generator for static text templates.
C#
1
star
48

mife-tutorial

Tutorial for a minimalistic microfrontend setup using React. :atom: 🚀
JavaScript
1
star
49

ModernCS

Examples for my presentation regarding C# for professionals
C#
1
star
50

schaaf.js

Example code for the "custom JS framework" session at My Coding Zone (5th of April 2024).
JavaScript
1
star
51

spaceshoot-sample-pilet

A pilet running the infamous SpaceShoot game for the sample-piral app shell. 👾
TypeScript
1
star
52

SpiderSample

A short sample code for demonstrating some features of the Spider programming language.
JavaScript
1
star
53

ts-service-boilerplate

Example boilerplate code for writing a Node.js service in TypeScript incl. OpenAPI spec generation and unit testing.
TypeScript
1
star
54

msdevrgb-web2018-demo

Demo code derived during the talk about Web Development 2018 at the Microsoft Developer Group in Regensburg.
TypeScript
1
star
55

cz-lang

My Coding Zone stream project - create your own programming language
TypeScript
1
star
56

kras-swagger-injector

Mock web service APIs by providing Swagger YAML files. 💪
TypeScript
1
star
57

Chocolatey-Julia

Chocolatey package to install the Julia programming language.
PowerShell
1
star
58

FlorianRappl

My GitHub profile.
1
star
59

react-alpine

A proof of concept / idea for a JS-in-JS implementation to enable ultra-fast websites with some degree of interactivity.
TypeScript
1
star