/* Shows how to use both command line and config file. */ #include <boost/program_options.hpp> namespace po = boost::program_options; #include <iostream> #include <fstream> using namespace std; int main(int ac, const char* av[]) { try { po::options_description desc("Allowed options"); // Declare a group of options that will be // allowed only on command line po::options_description desc2("Generic options"); desc2.add_options() ("version,v", "", "print version string") ("help", "", "produce help message") ; // Declare a group of options that will be // allowed both on command line and in // config file po::options_description desc3("Configuration"); desc3.add_options() ("output,o", "file", "where to send output") ("magic", "value", "magic value for the program") .default_value("43") ; desc.add(desc2); desc.add(desc3); // Parse command line and store results. po::variables_map vm; po::options_and_arguments oa1 = parse_command_line(ac, av, desc); po::store(oa1, vm, desc); // Parse config file and store results. Note // that different set of allowed options is used. po::variables_map cfg_file_vm; ifstream ifs("multiple_sources.cfg"); po::options_and_arguments oa2 = parse_config_file(ifs, desc3); po::store(oa2, cfg_file_vm, desc3); // Chain the variable maps vm.next(&cfg_file_vm); if (vm.count("help")) { cout << desc << "\n"; return 0; } if (vm.count("version")) { cout << "Multiple sources example, version 1.0\n"; return 0; } if (!vm["output"].empty()) cout << "output = " << vm["output"].as<string>() << "\n"; // This would output the value of 'magic' given on command line // If there's no value on command line, the value from // config file will be used. If there's no value even // there, then default value, "43", given in option // declaration, will be used. cout << "magic = " << vm["magic"].as<int>() << "\n"; } catch(exception& e) { cout << e.what() << "\n"; return 1; } return 0; }