基本用法

Boost 程序选项提供了一种简单而安全的方法来解析和处理命令行参数。

#include <boost/program_options.hpp>
#include <string>
#include <iostream>

int main(int argc, char** argv) {
  namespace po = boost::program_options;

  po::variables_map vm;
  po::options_description desc("Allowed Options");

  // declare arguments
  desc.add_options()
    ("name", po::value<std::string>()->required(), "Type your name to be greeted!");

  // parse arguments and save them in the variable map (vm)
  po::store(po::parse_command_line(argc, argv, desc), vm);

  std::cout << "Hello " << vm["name"].as<std::string>() << std::endl;

  return 0;
}

编译并运行:

 $ g++ main.cpp -lboost_program_options && ./a.out --name Batman
Hello Batman

你可以输出 boost::program_options::options_description 对象以打印预期的参数格式:

std::cout << desc << std::endl;

会产生:

Allowed Options:
  --name arg                Type your name to be greeted!