问题
I'm struggling to get boost program options to work properly. I need to be able to start my program from the terminal window (Linux) with an optional argument that takes a value. No matter what I did, this would not work; no matter what value I typed from the terminal, it just returned the default value. Furthermore, if I did not include the option in my termina command, it returned with
terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injec tor<std::logic_error> >'
what(): character conversion failed
Aborted (core dumped)
So I found a minimal example on the internet to see if it was something I had done wrong. Here is the example I found that does a similar thing that I need:
#include <iostream>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
int main (int argc, char* argv[]) {
po::options_description desc("Usage");
desc.add_options()
("robots", po::value<int>()->default_value(3),
"How many robots do you want to send on a murderous rampage?");
po::variables_map opts;
po::store(po::parse_command_line(argc, argv, desc), opts);
try {
po::notify(opts);
}
catch (std::exception& e) {
std::cerr << "Error: " << e.what() << "\n";
return 1;
}
int nRobots = opts["robots"].as<int>();
// automatically assigns default when option not supplied by user!!
std::cout << nRobots << " robots have begun the silicon revolution"
<< std::endl;
return 0;
}
This does exactly the same thing however, and I am starting to think this is either a bug in Boost (unlikely I guess) or something about my system that it doesn't like?
Could anybody hint at what might be wrong please? Thanks
回答1:
I ran into the exact same problem transitioning from 1.58
to 1.61
.
My problem was that I was linking 1.61
boost header code with old 1.58
shared libraries.
You may have installed a newer version of boost, but that doesn't mean you still aren't linking with old boost libraries. Check your linker. Check your system files.
A good check you can do on your program, is to run it through gdb
, have it crash, and look at the backtrace (bt). It will show the boost version numbers in the backtrace. See if it matches what you expected.
If relevant, I was on Ubuntu and built from source:
sudo ./bootstrap.sh --prefix=/usr
sudo ./b2 install threading=multi link=shared
This resulted in my library files being located at /usr/lib/libboost*
.
However, my linker was looking in /usr/lib/x86_64-linux-gnu/libboost*
.
A simple cp -Pf
over the old files solved my problem.
来源:https://stackoverflow.com/questions/37331901/c-boost-program-options-always-giving-default-value