Skip to content

Boost:ProgramOptions

The program_options library allows program developers to obtain program options, that is (name, value) pairs from the user, via conventional methods such as command line and config file.

Why would you use such a library, and why is it better than parsing your command line by straightforward hand-written code?

  • It's easier. The syntax for declaring options is simple, and the library itself is small. Things like conversion of option values to desired type and storing into program variables are handled automatically.
  • Error reporting is better. All the problems with the command line are reported, while hand-written code can just misparse the input. In addition, the usage message can be automatically generated, to avoid falling out of sync with the real list of options.
  • Options can be read from anywhere. Sooner or later the command line will be not enough for your users, and you'll want config files or maybe even environment variables. These can be added without significant effort on your part.

Simple example

간단한 사용방법은 아래와 같다.

namespace po = boost::program_options;
// ...
// Declare the supported options.
po::options_description desc("Allowed options");
desc.add_options()
    ("help", "produce help message")
    ("compression", po::value<int>(), "set compression level")
;

po::variables_map vm;
po::store(po::parse_command_line(ac, av, desc), vm);
po::notify(vm);    

if (vm.count("help")) {
    cout << desc << "\n";
    return 1;
}

if (vm.count("compression")) {
    cout << "Compression level was set to " 
 << vm["compression"].as<int>() << ".\n";
} else {
    cout << "Compression level was not set.\n";
}

아래와 같이 사용할 수 있다.

$ bin/gcc/debug/first
Compression level was not set.
$ bin/gcc/debug/first --help
Allowed options:
  --help                 : produce help message
  --compression arg      : set compression level
$ bin/gcc/debug/first --compression 10
Compression level was set to 10.

Favorite site