0

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;
}
user1587451
  • 978
  • 3
  • 15
  • 30

1 Answers1

2

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;
}
Community
  • 1
  • 1
luk32
  • 15,812
  • 38
  • 62
  • I've found the reason why I've putted notify after `if (flag)`. Due to other options... If some other required option is not provided by the user, notify will throw. Even if `help`-flag is provided. That's an use case my example did not show X-/ But anyway, my example/question is solved by your answer, so I mark it. – user1587451 Jan 20 '17 at 02:03