boost Basic Usage


Boost program options provides a simple and safe way to parse and handle command line arguments.

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

int main(int argc, char** argv) {
  namespace po = boost::program_options;

  po::variables_map vm;
  po::options_description desc("Allowed Options");

  // declare arguments
    ("name", po::value<std::string>()->required(), "Type your name to be greeted!");

  // parse arguments and save them in the variable map (vm)
  po::store(po::parse_command_line(argc, argv, desc), vm);

  std::cout << "Hello " << vm["name"].as<std::string>() << std::endl;

  return 0;

Compile and run with:

 $ g++ main.cpp -lboost_program_options && ./a.out --name Batman
Hello Batman

You can output a boost::program_options::options_description object to print the expected argument format:

std::cout << desc << std::endl;

would produce:

Allowed Options:
  --name arg                Type your name to be greeted!