Reputation: 1008
Code below uses po::bool_switch(&flag)
in hope of automatically assigning the correct value to flag
.
My compile command is clang++ -std=c++11 test.cpp -o test -lboost_program_options
So I run the program with ./test -h
which shows no help message.
Why so?
#include <iostream>
#include <boost/program_options.hpp>
namespace
{
namespace po = boost::program_options;
}
int main(int ac, char ** av)
{
bool flag;
po::options_description help("Help options");
help.add_options()
( "help,h"
, po::bool_switch(&flag)->default_value(false)
, "produce this help message" );
po::variables_map vm;
po::parsed_options parsed
= po::parse_command_line(ac,av,help);
po::store(po::parse_command_line(ac,av,help),vm);
if (flag)
{
std::cout << help;
}
po::notify(vm);
return 0;
}
Upvotes: 0
Views: 1164
Reputation: 16070
You should call notify
after parsing and storing arguments. store
just fills in internal data structures of variables_map
. notify
publishes them.
Your example is nearly exactly like the one in "Getting started section" in tutorial.
And here they give a pretty bold warning not to forget it:
Finally the call to the notify function runs the user-specified notify functions and stores the values into regular variables, if needed.
Warning: Don't forget to call the notify function after you've stored all parsed values.
This should work:
po::variables_map vm;
po::parsed_options parsed
= po::parse_command_line(ac,av,help);
po::store(po::parse_command_line(ac,av,help),vm);
po::notify(vm); // call after last store, and before accesing parsed variables
if (flag)
{
std::cout << help;
}
Upvotes: 2