Search code examples
c++boostcommand-line-argumentsboost-program-options

boost program_options: help vs. meaningful options


Is there an easy way to separate the help-option from the 'real' program options? In fact, is it possible to define a hierarchy of options, a la BNF:

options := help_options | program_options
help_options := '-h'
program_options := '-m1' mode1options | '-m2' mode2options
mode1options := number
...

Or is there a better way to achieve this? Should I revert to spirit?


Solution

  • The documentation describes how to separate options under the Option Groups and Hidden Options heading. It demonstrates defining multiple options_description objects and then using an all group for parsing the command line, but a visible group for displaying documentation:

    // Declare an options description instance which will include
    // all the options
    options_description all("Allowed options");
    all.add(general).add(gui).add(backend);
    
    // Declare an options description instance which will be shown
    // to the user
    options_description visible("Allowed options");
    visible.add(general).add(gui);
    
    variables_map vm;
    store(parse_command_line(ac, av, all), vm);
    
    if (vm.count("help")) 
    {
        cout << visible;
        return 0;
    }
    

    Although the Program_options library lets you customize some of the syntax (see Non-conventional Syntax and Custom Validators), it doesn't offer a way of defining a custom grammar. If you want to define the grammar of the command line, use a different tool.