【问题标题】:Parse prefix arguments with boost::program_options?使用 boost::program_options 解析前缀参数?
【发布时间】:2026-02-13 23:30:02
【问题描述】:

我需要解析带有 boost::program_options 前缀的参数,例如 -O1 / -O2 / -O3,所以 -O 是前缀,后跟优化级别作为数字。

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

  cl::opt<char>
     OptLevel("O",
         cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
                  "(default = '-O2')"),
         cl::Prefix,
         cl::ZeroOrMore,
         cl::init(' '));

【问题讨论】:

  • 我不知道为什么这个问题被否决 - 这是现实生活中的例子

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


【解决方案1】:

这是我的想法:注意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

【讨论】:

  • 我能够使用“O1”作为long名称(("O1", po::value&lt;bool&gt;(&amp;OptLevelO1) -&gt; zero_tokens() -&gt; default_value(false), "Optimization level 1. Similar to clang -O1"))和.style(po::command_line_style::default_style | po::command_line_style::allow_long_disguise) // to allow passing Long arguments using single dash ('-')
  • @4ntoine 实际上,这本来是我的方法,但您特别要求整数参数变体(我期待“我们无法添加数百个选项来促进 -O438 :))