Skip to content

Program Options Tutorial

sarthak-0415 edited this page Jul 1, 2015 · 4 revisions
  1. options_description class to declare the allowed option.

  2. add_options function to actually declare eaxh option and its value type.

    • a. we init the opttion and its property in this function only.
    • b. function takes following arguments i. options name, ii. value type iii. required or not iv. default_value v. description.
    • c. for ex : ("clean",po::value<bool>(&clean)->default_value(false),"drop previously created tables (default: false)") ;
  3. Object of class variable_map which stores options vs value.

  4. Store function stores the options from starndard input into the vm object

  5. Use the map top actually use the options.

  6. Options details-

    • a. we can store the value of an options both in a map and a variable :
    	int opt;
    	po::value<int>(&opt)->default_value(10);
    
    • b. We can use small names as well ("clean,c",val...);
    • c. Vectors are supported (vlaue< vector< int > >(&opt));
  7. There are some options that do not require a name, those are called positional_options, which can be handled described below:

    	int opt;
    	po::options_description desc("Allowed OPtions");
    	desc.add_options()
    	("help","Help mesasage"),
    	("optimization,o",value<int>(&opt),"optimizationa level");
    	;
    
    	po::variable_map vm;
    	po::positional_option_description p;
    	p.add("input_file",-1);
    
    	po::store(po::command_line_parser(ac,av).options(desc).postition(p).run(),vm);
    	po::notify vm;
    
  8. Multiple Sources -> User can add options from command line as well as config file and some options should be hidden to the user. We can add several options_descriptions for a structure also

    • generic -Only command line
    • config - Only config file.
    • hidden -both but hidden

    8.1 add composing method to merge several values in an option :

    	po::value< vector< string>>()->composing(),"..."); 
    
  9. For parsing config file, additionally call parse_config_file and call store again.

  10. use count function to check whether any options have any associated value or not :

    	if (vm.count("help")) {		
    	    cout << od_desc << "\n";		
    	    return 0;		
    	}
    
  11. Value are used as follows: file = vm["file"].as<string>();