The C++ standard adopted many Boost libraries; however, you won't find Boost.ProgramOptions even in C++17. Currently, there's no plan to adopt it into C++2a.
The ProgramOptions library is very powerful and has many features. Here's how to:
- Parse configuration option values directly into a variable and make that option a required one:
int oranges_var = 0;
desc.add_options()
// ProgramOptions stores the option value into
// the variable that is passed by pointer. Here value of
// "--oranges" option will be stored into 'oranges_var'.
("oranges,o", opt::value<int>(&oranges_var)->required(),
"oranges you have")
- Get some mandatory string option:
// 'name' option is not marked with 'required()',
// so user may not provide it.
("name", opt::value<std::string>(), "your name")
- Add short name for apple, set 10 as a default value for apples:
// 'a' is a short option name for apples. Use as '-a 10'.
// If no value provided, then the default value is used.
("apples,a", opt::value<int>()->default_value(10),
"apples that you have");
- Get the missing options from the configuration file:
opt::variables_map vm;
// Parsing command line options and storing values to 'vm'.
opt::store(opt::parse_command_line(argc, argv, desc), vm);
// We can also parse environment variables. Just use
// 'opt::store with' 'opt::parse_environment' function.
// Adding missing options from "apples_oranges.cfg" config file.
try {
opt::store(
opt::parse_config_file<char>("apples_oranges.cfg", desc),
vm
);
} catch (const opt::reading_file& e) {
std::cout << "Error: " << e.what() << std::endl;
}
The configuration file syntax differs from the command-line syntax. We do not need to place minuses before the options. So, our apples_oranges.cfg file must look like this:
oranges=20
- Validate that all the required options were set:
try {
// `opt::required_option` exception is thrown if
// one of the required options was not set.
opt::notify(vm);
} catch (const opt::required_option& e) {
std::cout << "Error: " << e.what() << std::endl;
return 2;
}
If we combine all the mentioned tips into a single executable, then its help command will produce this output:
$ ./our_program.exe --help
All options:
-o [ --oranges ] arg oranges that you have
--name arg your name
-a [ --apples ] arg (=10) apples that you have
--help produce help message
Running it without a configuration file will produce the following output:
$ ./our_program.exe
Error: can not read options configuration file 'apples_oranges.cfg'
Error: the option '--oranges' is required but missing
Running the program with oranges=20 in the configuration file will generate ++, because the default value for apples is 10:
$ ./our_program.exe
Fruits count: 30