最近要写一个exe命令行参数的东西。类似于:
abc.exe -t -input D:\abc.txt
这样的东西。因此网上搜了一下,真的有不少现成的库呢。大家说,Boost就有相关的东西,于是我决定就用Boost的program_option来做argument parsing了。
他们的库用起来也不是那么复杂,Tutorial请点此。关键是有一份Getting Started code, 就在网站上
#include <boost/program_options.hpp>
namespace po = boost::program_options;
int main(int ac, char* av[])
{
// Declare the supported options.
// Also noted that "help" definition line only got two string parameters,
// so it don't have following argument
// But "compression" got a following 'int' argument, receiving argument
// input like '--compression 1'
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("compression", po::value<int>(), "set compression level")
;
// Parsing the user input argument, stored in
// a map 'vm' (hash-map alike structure)
po::variables_map vm;
po::store(po::parse_command_line(ac, av, desc), vm);
po::notify(vm);
// For "--help" option, determined if it appearred in para list
if (vm.count("help")) {
cout << desc << "\n";
return 1;
}
// For "--compression" opition, first need determine its existence,
// then will need to retrive its value using ".as<int>()" function.
if (vm.count("compression"))
{
cout << "Compression level was set to "
<< vm["compression"].as<int>() << ".\n";
} else {
cout << "Compression level was not set.\n";
}
}
这行code还是很简单的。大致来说分为三步:
- 定义
你需要首先定义一个options list, 如代码里的 desc 变量。然后你可以通过.add_options()方法,来快速为这个list添加支持的定义。你可以定义一个后面不需要跟参数的option,比如”–help”;也可以定义一个需要跟参数的option,比如上文中需要后面跟着一个int的”–compression”参数。
还有个很好的东西,就是你可以为每个option添加一段说明文字,然后你可以直接在程序中用cout << desc << endl;
来输出这段说明文字。很不错
- 解析
定义好之后,调用po::variables_map vm; po::store(po::parse_command_line(ac, av, desc), vm); po::notify(vm);
这三句话,将main函数的输入参数 int main(int ac, char* av[]) 中的 ac 和 av进行解析,将解析结果存入到一个 variables_map 类型的叫做 vm 的字典 中去。
- 判断是否存在某参数
这就跟hashtable的用法一样了。用.count()方法来判断vm是否包含某个option, 用 [] 操作符来取相应option的值(当然必须要在定义中定义了这是个有值的option,比如”–help”就不行!)
注意,在这个例子中,需要用户输入在参数前面输入两个横线(double dash)作为参数的引导,比如–help, 比如–compression,这很不习惯啊。于是我又查了查,以关键字 boost program_options single dash 搜索了一下,找打了>>这个<<网址,然后看了看原来这是为了符合Unix规范。
当然也可以告诉boost去解析单横线(single dash)引导的命令,只需要申明一个option style,然后在刚刚解析参数的时候,把这个style作为参数传入即可:
po::command_line_style::style_t style = po::command_line_style::style_t( po::command_line_style::unix_style ¦ po::command_line_style::case_insensitive ¦ po::command_line_style::allow_long_disguise ); po::store(po::parse_command_line(ac, av, desc, style), vm);
然后我就把这个command line utility写完了!Good!

