Snippets

Federico Fuga Boost::program_option usages

Created by Federico Fuga last modified
// ...

#include <boost/program_options.hpp>

namespace po = boost::program_options;

int main(int argc, char *argv[])
{
    int opt;
    
    // Declare the supported options.
    po::options_description desc("Allowed options");
    desc.add_options()
            ("help,h", "produce help message")
            ("longoption", "This is a long option: --longoption.")
            ("option2,o", "This is a shorthand option with long option, use --option2 or -o")
            (",O", "This is a shorthand only option: use -O only")     // see below about how to access
            ("required,r", po::value<std::strubg>()->required(), "a mandatory option with string argument: -r string") 
                // NOTE: required arguments will prevent --help from work. You can use     count("required") == 0   instead...
            ("list", po::value<std::vector<int>>(), "List of values: --list 1 --list 2 --list 3")
            ("opt", po::value(&opt), "Another option with argument, directly into the variable")
            ("default", po::value<std::string>()->default_value("the-fault"), "optional argument with default value")
            ;

    po::variables_map vm;
    po::store(po::parse_command_line(argc, argv, desc), vm);
    po::notify(vm);

    if (vm.count("help")) {
        std::cout << desc << "\n";
        return 1;
    }

    std::string required_string = vm["required"].as<std::string>();
    auto list = vm["list"].as<std::vector<int>>();
    
    if (vm.count("-O")) {
        // do something with shorthand option
    }
    // ...
}

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.