Reputation: 61
I'm trying to parse command line arguments with boost. Here's my code (I am only including the part I need help with):
#include <iostream>
#include <iterator>
#include <boost/program_options.hpp>
using std::cerr;
using std::cout;
using std::endl;
namespace po = boost::program_options;
try {
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("compression", po::value<double>(), "set compression level");
po::variables_map vm;
po::store(po::parse_command_line(ac, av, desc), vm);
po::notify(vm);
if (vm.count("help")) {
cout << desc << "\n";
return 0;
}
if (vm.count("compression")) {
cout << "Compression level was set to "
<< vm["compression"].as<double>() << ".\n";
} else {
cout << "Compression level was not set.\n";
}
}
catch(exception& e) {
cerr << "error: " << e.what() << "\n";
return 1;
}
catch(...) {
cerr << "Exception of unknown type!\n";
}
I have my main function set to:
main(int argc, char const *argv[])
but, the code I was following https://github.com/boostorg/program_options/blob/develop/example/first.cpp contained these parameters:
int main(int ac, char* av[])
When I comile it, it spits out this and I am completely lost:
Upvotes: 4
Views: 19255
Reputation: 986
You also forgot to include exception - here is your code working..
#include <iostream>
#include <iterator>
#include <boost/program_options.hpp>
#include <exception>
using std::cerr;
using std::cout;
using std::endl;
using std::exception;
namespace po = boost::program_options;
int main(int ac, char** av){
try {
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("compression", po::value<double>(), "set compression level");
po::variables_map vm;
po::store(po::parse_command_line(ac, av, desc), vm);
po::notify(vm);
if (vm.count("help")) {
cout << desc << "\n";
return 0;
}
if (vm.count("compression")) {
cout << "Compression level was set to "
<< vm["compression"].as<double>() << ".\n";
} else {
cout << "Compression level was not set.\n";
}
}
catch(exception& e) {
cerr << "error: " << e.what() << "\n";
return 1;
}
catch(...) {
cerr << "Exception of unknown type!\n";
return 1;
}
return 0;
}
Compile this with
g++ -std=c++11 cmd.cpp -l boost_program_options
And you should be fine
Actually you can leave out "std=c++11" if you want to. I have tried it with both and its ok
Upvotes: 10