使用boost :: program_options解析前缀参数?

时间:2014-10-14 16:56:16

标签: boost llvm boost-program-options command-line-parsing

我需要用{:: 1}} / -O1 / -O2之类的boost :: program_options来解析带有前缀的参数,因此-O3是前缀,后跟优化级别为数字。< / p>

它是使用LLVM CommandLine支持声明的,我需要这样:

-O

1 个答案:

答案 0 :(得分:3)

这是我的想法:请注意使用po::command_line_style::short_allow_adjacent

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

namespace po = boost::program_options;

int main(int argc, char** argv)
{
    int opt;
    po::options_description desc("Allowed options");
    desc.add_options()
        ("help", "produce help message")
        ("optimization,O", po::value<int>(&opt)->default_value(1), "optimization level")
        ("include-path,I", po::value< std::vector<std::string> >(), "include path")
        ("input-file", po::value< std::vector<std::string> >(), "input file")
        ;

    po::variables_map vm;
    po::store(
            po::parse_command_line(argc, argv, desc, 
                po::command_line_style::allow_dash_for_short |
                po::command_line_style::allow_long |
                po::command_line_style::long_allow_adjacent |
                po::command_line_style::short_allow_adjacent | 
                po::command_line_style::allow_short
            ),
            vm);

    po::notify(vm);

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

    std::cout << "Optimization level chosen: " << opt << "\n";
}

Live On Coliru

那样

./a.out -O23
./a.out -O 4
./a.out -I /usr/include -I /usr/local/include
./a.out --optimization=3

打印

Optimization level chosen: 23
Optimization level chosen: 4
Optimization level chosen: 1
Optimization level chosen: 3