2

I have the following code in testpo.cpp:

#include <iostream>
#include <boost/program_options.hpp>
#include <fstream>

int main(int argc, char* argv[]) {

  namespace po = boost::program_options;
  po::options_description config_descriptor;
  po::variables_map vm;

  config_descriptor.add_options()
  ("var1", po::value<int>()->required(), "var1");
  //po::store(po::parse_config_file(input_config_file, config_descriptor, false), vm);
  po::store(po::parse_command_line(argc, argv, config_descriptor), vm);
  po::notify(vm);

  try {
    std::cout << vm.count("var1") << std::endl;
    std::cout << "Count printed" << std::endl;
    if (vm.count("var1") > 0) {
      std::cout << "Imhere\n";
      std::cout << "var1: " << vm["var1"].as<int>() << std::endl;
    } else {
      std::cout << "Missing var1 in config file" << std::endl;
    }
  } catch (std::exception& e) {
    std::cout << "Exception: " << e.what() << std::endl;
  }

}

I compile using the following command:

g++ -std=c++11 testpo.cpp -lboost_program_options

And I run it like this:

./a.out --var1 10

I get the following output:

1
Count printed
Imhere
Exception: boost::bad_any_cast: failed conversion using boost::any_cast

I have already looked at this but it doen't seem to help. I can't find what I'm doing wrong.

My system's relevant configuration:

g++ (Ubuntu 5.2.1-22ubuntu2) 5.2.1 20151010
Boost version: 1.58

When I run it on another system it works, configuration:

g++ (GCC) 4.8.3 20140911 (Red Hat 4.8.3-9)
Boost version: 1.53

Is it a bug in boost?

Community
  • 1
  • 1
nishantsingh
  • 4,537
  • 5
  • 25
  • 51
  • not a bug, just boost being useless with the way it throws a context-less exception. A bit like your C++ compiler just telling you your code didn't compile without giving any description of the error. – CashCow Oct 05 '16 at 10:28
  • This works fine for me using boost 1.58 and g++ (Ubuntu 5.4.0-6ubuntu1~16.04.2) 5.4.0 20160609. Maybe try running under valgrind in hope to get some hints? – doqtor Oct 05 '16 at 12:07
  • Also works fine for me [boost 1.61.0, g++ 6.2.1, Suse Tumblweed]. Have you tried printing `vm["var1"]` as a string by way of a check -- just in case there's anything funny going on? – G.M. Oct 05 '16 at 14:11

1 Answers1

0

Since i just had the same problem, for future reference i will add my answer here.

The exception is thrown because of a missing return statement in your

int main

edit: strike that. I'm stupid and forgot a break in a case statement.

IjonTichy
  • 309
  • 1
  • 11
  • With modern C/C++ compilers, an explicit return [is not needed](https://stackoverflow.com/q/276807). – Christian Garbin Mar 09 '20 at 22:05
  • Thank you @ChristianGarbin i did not know that. I'm using gcc 9.2 with cmake 3.16 and boost 1.69. The exception goes away when i add a return statement to my main though. I will look further into this and come back when i found the problem. – IjonTichy Mar 11 '20 at 19:59