Search code examples
c++boostboost-program-options

Why is boost::program_options accepting chopped words?


I have the following program:

#include <boost/program_options.hpp>

bool check_options(int argc, char** argv)
{
    using namespace boost::program_options;
    variables_map vm;

    // Command line options
    std::string cfg_file_name;
    options_description cmd_line("Allowed options");
    cmd_line.add_options()
        ("help", "produce this help message")
        ;

    store(parse_command_line(argc, argv, cmd_line), vm);
    notify(vm);    
    if(vm.count("help")) 
    {
        std::cout << cmd_line << std::endl;
        return false;
    }
    return true;
}

int main(int argc, char** argv)
{
    if(!check_options(argc, argv))
        return 1;
    return 0;
}

When I run it with ./myprg --help I get the result I expect:

Allowed options:
  --help                produce this help message

However I get the same result even if I run: ./myprg --h or ./myprg --he or ./myprg --hel. Shouldn't those last options throw an error?


Solution

  • Seems like accepting partial matches is the default_style for boost::option.

    According to an answer at the Boost site http://lists.boost.org/boost-users/2007/02/25861.php

    this default can be changed to require a full match, by passing an extra parameter to parse_command_line.

    EDIT by OP: Actually instead of parse_command_line I had to use the more general command_line_parser (which allows style changings), thus replacing the store(... line with this one:

    store(command_line_parser(argc, argv).options(cmd_line).style(command_line_style::default_style & ~command_line_style::allow_guessing).run(), vm);