Main   Classes   Namespace members   Examples   Recipes   Rationale   Related pages

Multiple modules

Large programs are likely to have several modules which want to use some options. One possible approach is show here.
See also:
I have several separate modules which must controlled by options. What am I to do?
/* Shows how options for two modules can be separated. */

#include <boost/program_options.hpp>
namespace po = boost::program_options;


#include <iostream>
#include <fstream>
using namespace std;

class Module1 {
public:
    po::options_description get_options()
    {
        po::options_description desc("Module1 options");
        desc.add_options()
        ("server", "arg", "the address of server to use")
        ("proxy", "arg", "proxy")
        ;
    return desc;
    }

    void do_something(map<string, string>& options)
    {
        cout << "Module1::do\n";
        for (map<string, string>::iterator i = options.begin();
             i != options.end();
             ++i)
        {
            cout << i->first << "=" << i->second << "\n";
        }
    }
} m1;

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")    
        ("language", "arg", "language to use")
            ;

    desc.add(desc2);
        desc.add(m1.get_options());
    
        po::options_and_arguments oa1 = parse_command_line(ac, av, desc);

        map<string, string> m1_options;
    po::variables_map vm;
    // Store all options in vm
        po::store(oa1, vm, desc);
    // Store options, provided by m1
    po::store(oa1, m1_options, m1.get_options());
        
        if (vm.count("help")) {
            cout << desc << "\n";
            return 0;
        }

        if (vm.count("version")) {
            cout << "Multiple modules example, version 1.0\n";
            return 0;
        }   

        m1.do_something(m1_options);
    }
    catch(exception& e)
    {
        cout << e.what() << "\n";
        return 1;
    }    
    return 0;
}

Generated on 23 May 2003 with
doxygen