Print help for both normal and positional args with boost::program_options

nuoritoveri picture nuoritoveri · Jan 2, 2013 · Viewed 7.1k times · Source

When you use Boost library program_options it is very easy to print help for your program:

boost::program_options::variables_map options;
boost::program_options::options_description optionsDesc;
boost::program_options::positional_options_description positionalOptionsDesc;
//...
if(options.count("help"))
{
    cerr << optionsDesc << endl;
}

But how do you add the options from positional_options_description to the help message? In the tutorial I can see the output of such set-up, at the end of the section:

http://www.boost.org/doc/libs/1_52_0/doc/html/program_options/tutorial.html#id2607297

The option input-file is printed in help and it is positional. But I can't see the code. Is there an build-in way to print it, like with options_description or you have to do it manually? Apparently the << does not work for positional_options_description, the compilation error is:

error: cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’

Answer

Bee picture Bee · Jan 2, 2013

Notice that streaming description only prints out the options. It does not print the name of the program or the actual description of what the program does. You should manually print any positional parameter you have as part of the output message:

Instead of

if (vm.count("help")) {
    cout << "Usage: options_description [options]\n";
    cout << desc;
    return 0;
}

You could easily say

if (vm.count("help")) {
    cout << "Usage: " << argv[0] << " [options] <description of positional 1> <description of positional 2> ...\n";
    cout << desc;
    return 0;
}