-
Notifications
You must be signed in to change notification settings - Fork 0
Getting Started
rail5 edited this page Feb 13, 2026
·
3 revisions
- C++20 compiler
-
getopt_long(XGetOpt includes<getopt.h>and expects conventionalgetopt_longbehavior)
XGetOpt is header-only: add xgetopt.h to your include path and #include "xgetopt.h".
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, orXGetOpt::OptionalArgument. -
arg_placeholder: optional placeholder used in help output ("file","path", etc.).
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;XGetOpt::OptionSequence options = parser.parse(argc, argv);- Throws
std::runtime_erroron unknown options or missing required arguments. - Non-option arguments are collected into
options.getNonOptionArguments().
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.
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;
}
}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)
- XGetOpt relies on
getopt_longandREQUIRE_ORDERbehavior. It is not a POSIX-only implementation. - Parsing uses global
getoptstate. Do not callparseconcurrently from multiple threads.