基本用法
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!