A cross-platform C++ library for parsing command line arguments
Description
LibCppCmdLine is a modern, lightweight, cross-platform C++ command line parsing library. It provides a set of classes for parsing command line arguments passed to a program via the main() function and populating command line parameters with values as a result of parsing.
A program that uses this library will:
- Define and create command line parameters.
- Create a new command line parser.
- Add the command line parameters to the parser.
- Parse the command line arguments with the parser.
- Examine the parameters that were populated by the parser.
The library uses the C++ Standard Template Library (STL) and therefore has no major external dependencies. It is lightweight enough to be added directly to a program's code base, though it can also be precompiled and linked statically or dynamically if desired. The library uses exceptions only to enforce class invariants and prevent programming errors. In practice, exceptions are only generated if parameters are defined incorrectly or duplicate parameters are added, so consumer code typically does not need try/catch blocks.
- Note
- The tests for this library do have an external dependency: GoogleTest. However, the tests are only needed when testing changes to the library itself and are not needed for a program that simply includes the library as-is.
Features
- Lightweight.
- Cross-platform.
- No external dependencies.
- Designed to be added and compiled straight into your program's code base.
- Supports two types of options and two types of positional parameters.
- Options can have either the Windows or Unix-style prefix.
- Standard options act like simple switches.
- Value options support multiple values and their own option parameters.
- Positional parameters come in single-value or multi-value varieties.
- The parser can generate usage and help information based on the parameters.
Limitations
- Only supports ASCII command line arguments.
- Not designed for programs with a highly complex command line use case.
Namespace
Everything in this library is contained within the CmdLine namespace.
The CmdLine namespace encapsulates all objects and functions related to command line argument parsing. Command line arguments are the string arguments passed to the main() function from the operating system, typically from a command line interface (CLI).
Key Classes
The following classes are necessary to parse command line arguments.
Key Structs
The following structs are necessary to define command line parameters.
Including the Library in Your Project
LibCppCmdLine builds a CMake target named LibCppCmdLine. After adding the library to your project, link that target to your executable or library:
target_link_libraries(YourTarget PRIVATE LibCppCmdLine)
Option 1: Add It as a Git Submodule
Add the repository as a submodule inside your project:
git submodule add https://github.com/stephenbonar/LibCppCmdLine external/LibCppCmdLine
git submodule update --init --recursive
Then include it from your top-level CMakeLists.txt:
cmake_minimum_required(VERSION 3.12)
project(YourProject)
set(LIBCPPCMDLINE_BUILD_TESTS OFF CACHE BOOL "" FORCE)
add_subdirectory(external/LibCppCmdLine)
add_executable(YourTarget src/main.cpp)
target_link_libraries(YourTarget PRIVATE LibCppCmdLine)
Use this approach when you want the library source checked into your repository and versioned alongside your project.
Option 2: Fetch It During CMake Configure
If you do not want to keep the library in your source tree, you can have CMake fetch it directly from Git during configuration with FetchContent:
cmake_minimum_required(VERSION 3.14)
project(YourProject)
include(FetchContent)
set(LIBCPPCMDLINE_BUILD_TESTS OFF CACHE BOOL "" FORCE)
FetchContent_Declare(
LibCppCmdLine
GIT_REPOSITORY https://github.com/stephenbonar/LibCppCmdLine.git
GIT_TAG main
)
FetchContent_MakeAvailable(LibCppCmdLine)
add_executable(YourTarget src/main.cpp)
target_link_libraries(YourTarget PRIVATE LibCppCmdLine)
If you want a reproducible build, replace GIT_TAG main with a specific tag, branch, or commit hash.
Header Include
Once linked, include the main library header in your source file:
#include "LibCppCmdLine.h"
Notes
- Set LIBCPPCMDLINE_BUILD_TESTS to OFF when embedding the library so your project does not also build this repository's GoogleTest-based test suite.
- The library target publishes its public include directory, so no extra target_include_directories() call is needed in the consuming target.
Examples
The example source files live in examples/ and are built when LIBCPPCMDLINE_BUILD_EXAMPLES=ON (default).
cmake -S . -B build -DLIBCPPCMDLINE_BUILD_EXAMPLES=ON
cmake --build build --target basic_example
cmake --build build --target value_option_example
Run them from the build output directory:
./build/examples/basic_example --help
./build/examples/value_option_example --help
Basic Parsing Example
This example shows how to define a program parameter, a standard option, and a required positional parameter, then parse argv.
#include <iostream>
#include <vector>
#include "LibCppCmdLine.h"
int main(int argc, char* argv[])
{
using namespace CmdLine;
programDef.
name =
"filesearch";
programDef.
description =
"searches files for lines that contain a pattern";
ignoreCaseDef.
description =
"ignores case when searching";
patternDef.
name =
"pattern";
Option ignoreCase(ignoreCaseDef);
std::vector<std::string> args(argv, argv + argc);
Parser parser(&program, args);
parser.Add(&ignoreCase);
parser.Add(&pattern);
{
std::cerr << parser.GenerateUsage() << '\n';
return 1;
}
if (parser.BuiltInHelpOptionIsSpecified())
{
std::cout << parser.GenerateHelp() << '\n';
return 0;
}
std::cout << "pattern: " << pattern.Value() << '\n';
std::cout << "ignore case: " << std::boolalpha
<< ignoreCase.IsSpecified() << '\n';
}
An ArgParam that represents a command line option.
Definition Option.h:52
Parses command line arguments.
Definition Parser.h:53
@ Success
Indicates parsing was successful.
Definition Parser.h:64
A Positional command line ArgParam.
Definition PosParam.h:44
A command line ArgParam populated by the program name.
Definition ProgParam.h:41
This Definition is used to construct an Option.
Definition Option.h:69
char shortName
The short name of the Option.
Definition Option.h:80
std::string longName
The long name of the Option.
Definition Option.h:92
std::string description
The description of the Option.
Definition Option.h:97
std::string name
Gets the name of the Param.
Definition Param.h:56
bool isMandatory
Determines if the Param is mandatory.
Definition Param.h:69
std::string description
Gets the description of the Param.
Definition Param.h:64
This definition is used to construct a PosParam.
Definition PosParam.h:50
This definition is used to construct a ProgParam.
Definition ProgParam.h:47
Example command lines:
filesearch test-pattern
filesearch --ignore-case test-pattern
filesearch -i test-pattern
Value Option Example
This example shows how to use a ValueOption with OptionParam objects to handle commands such as --edit artist=The Beatles --edit album=Revolver.
#include <iostream>
#include <vector>
#include "LibCppCmdLine.h"
int main(int argc, char* argv[])
{
using namespace CmdLine;
programDef.
name =
"mediaedit";
programDef.
description =
"prints and edits tags in media files";
artistDef.
name =
"artist";
filesDef.
name =
"filenames";
edit.Add(&artist);
edit.Add(&album);
std::vector<std::string> args(argv, argv + argc);
Parser parser(&program, args);
parser.Add(&edit);
parser.Set(&files);
{
std::cerr << parser.GenerateUsage() << '\n';
return 1;
}
for (const auto& value : edit.Values())
{
std::cout << "edit value: " << value << '\n';
}
if (artist.IsSpecified())
{
std::cout << "artist: " << artist.Value() << '\n';
}
if (album.IsSpecified())
{
std::cout << "album: " << album.Value() << '\n';
}
for (const auto& file : files.Values())
{
std::cout << "file: " << file << '\n';
}
}
A multi-value PosParam.
Definition MultiPosParam.h:47
Provides parameters for ValueOption values.
Definition OptionParam.h:52
A command line Option that is populated with values.
Definition ValueOption.h:63
This definition is used to construct a MutiPosParam.
Definition MultiPosParam.h:76
bool isMandatory
Determines if the MultiPosParam is mandatory.
Definition MultiPosParam.h:90
std::string description
The description of the MultiPosParam.
Definition MultiPosParam.h:85
std::string name
The name of the MultiPosParam.
Definition MultiPosParam.h:80
This definition is used to construct an OptionParam.
Definition OptionParam.h:58
This definition is used to construct a ValueOption.
Definition ValueOption.h:69
Example command line:
mediaedit --edit artist=The Beatles --edit album=Revolver track01.mp3 track02.mp3
API Documentation
The full documentation for the library is available here