-
Notifications
You must be signed in to change notification settings - Fork 591
Options
For this page, we will assume that there is a cxxopts::Options
object declared like so:
cxxopts::Options options(argv[0]);
To add options to the parser, use the function add_options
as in the following example:
options.add_options()("option", "description", value)
Where "option"
describes the option, "description"
is a description of the option for the help, and value
is an object describing the type of the argument to the option.
Options must have a long form, and may have a short form. To specify a command line option, the string "option"
has the form:
l,long
where the l,
is optional. This specifies an option whose long name is long
, and whose short name is l
.
The parameters to arguments can be parsed, rather than just being recognised as a string. In addition, multiple occurrences of an option can be pushed into a vector. To specify a type for a parameter, the function cxxopts::value
is used, which takes a template parameter specifying the type of a parameter, and an optional reference to a variable, into which the parsed value will be stored.
If the value type is omitted, it defaults to boolean, which takes no argument, and is used as a switch.
For example, the following example adds an option file
, with a short option f
, which takes a string:
options.add_options()
("f,file", "File", cxxopts::value<std::string>());
The next example adds an option verbose
, with a short option v
, and takes an integer which is parsed into a local variable:
int verbose = 0;
options.add_options()
("v,verbose", "Verbosity", cxxopts::value(verbose));
Options can be parsed into a vector, so that an option can appear multiple times on the command line. The following example adds the argument of each occurrence of --input
to a vector:
std::vector<std::string> input;
options.add_options()
("i,input", "Input", cxxopts::value(input));
Passing a std::string_view
for a cxxopts::value
is not supported. If it compiles, then the resulting value retrieved with as
will probably refer to undefined memory.
An option can be declared with a default or an implicit value, or both.
A default value is the value that an option takes when it is not specified on the command line. The following specifies a default value for an option:
cxxopts::value<std::string>()->default_value("value")
An implicit value is the value that an option takes when it is given on the command line without an argument. The following specifies an implicit value:
cxxopts::value<std::string>()->implicit_value("implicit")
If an option had both, then not specifying it would give the value "value"
,
writing it on the command line as --option
would give the value "implicit"
,
and writing --option=another
would give it the value "another"
.