3

I need to parse argument with prefix with boost::program_options like -O1 / -O2 / -O3, so -O is prefix followed by optimization level as number.

It's declared using LLVM CommandLine support like that and i need to like that:

  cl::opt<char>
     OptLevel("O",
         cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
                  "(default = '-O2')"),
         cl::Prefix,
         cl::ZeroOrMore,
         cl::init(' '));
Sam Miller
  • 23,808
  • 4
  • 67
  • 87
4ntoine
  • 19,816
  • 21
  • 96
  • 220

1 Answers1

3

This is my idea: note the use of 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

So that

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

Prints

Optimization level chosen: 23
Optimization level chosen: 4
Optimization level chosen: 1
Optimization level chosen: 3
sehe
  • 374,641
  • 47
  • 450
  • 633
  • i was able to get it just using "O1" as **long** name (`("O1", po::value(&OptLevelO1) -> zero_tokens() -> default_value(false), "Optimization level 1. Similar to clang -O1")`) and `.style(po::command_line_style::default_style | po::command_line_style::allow_long_disguise) // to allow passing Long arguments using single dash ('-')` – 4ntoine Oct 17 '14 at 11:30
  • @4ntoine Actually, that would have been my approach, but you specfically asked for the integer argument variation (and I was anticipating "We can't add hundreds of options to facilitate `-O438` :)) – sehe Oct 17 '14 at 11:31