Skip to content

Getting Started

rail5 edited this page Feb 13, 2026 · 3 revisions

Getting Started

Requirements

  • C++20 compiler
  • getopt_long (XGetOpt includes <getopt.h> and expects conventional getopt_long behavior)

XGetOpt is header-only: add xgetopt.h to your include path and #include "xgetopt.h".

Defining options

Options are defined at compile time using the XGetOpt::Option<...> template:

constexpr XGetOpt::Option<'h', "help",
	"Show this help message and exit",
	XGetOpt::ArgumentRequirement::NoArgument> HelpOption;
constexpr XGetOpt::Option<1001, "output",
	"Specify output file",
	XGetOpt::ArgumentRequirement::RequiredArgument,
	"FILE"> OutputOption;

Where:

  • shortopt: a printable ASCII character like 'h', or a unique integer (commonly 1000+) for long-only options.
  • longopt: a string literal like "help" or "output" (use "" for short-only options).
  • description: help text.
  • requirement: XGetOpt::NoArgument, XGetOpt::RequiredArgument, or XGetOpt::OptionalArgument.
  • arg_placeholder: optional placeholder used in help output ("file", "path", etc.).

Creating a parser

Create an OptionParser instance with your options as template parameters:

constexpr XGetOpt::OptionParser<
	XGetOpt::Option<'h', "help", "Show help", XGetOpt::ArgumentRequirement::NoArgument>,
	XGetOpt::Option<1001, "output", "Specify output file", XGetOpt::ArgumentRequirement::RequiredArgument, "FILE">
> parser;

Parsing arguments

Parse everything (most common)

XGetOpt::OptionSequence options = parser.parse(argc, argv);
  • Throws std::runtime_error on unknown options or missing required arguments.
  • Non-option arguments are collected into options.getNonOptionArguments().

Parse until a condition

If you need to stop at the first non-option argument or stop before the first error, use:

auto [options, remainder] = parser.parse_until<XGetOpt::BeforeFirstNonOptionArgument>(argc, argv);

See Stop Conditions and Remainders for precise behavior.

Handling parsed options

Iterate over the options:

for (const auto& opt : options) {
	switch (opt.getShortOpt()) {
		case 'h':
			std::cout << parser.getHelpString();
			break;
		case 'o':
			if (opt.hasArgument()) {
				std::cout << "output=" << opt.getArgument() << "\n";
			}
			break;
	}
}

Help string

parser.getHelpString() returns a compile-time generated help string.

  • Wrapped to 80 columns for descriptions
  • Displays required args as <arg> and optional args as [=arg] (or [arg] for short-only)

Potential pitfalls

  • XGetOpt relies on getopt_long and REQUIRE_ORDER behavior. It is not a POSIX-only implementation.
  • Parsing uses global getopt state. Do not call parse concurrently from multiple threads.

Clone this wiki locally