[C++boost] program parameter Item resolution Library Program_options usage Guide

Source: Internet
Author: User

Introduced

Program options are a series of name=value pairs, program_options allow program developers to obtain these parameter entries via command line and configuration file (config files).

Why do you need such a library? Why is it better than you to manually write code to break down command line parameters?

    • Easier to use. The syntax for defining parameter handling is simple and the library itself is small. Things like converting parameter values to a specified type and saving a parameter value to a variable are handled automatically.
    • Error reporting is more friendly. Command-line arguments that can report errors. In addition, this library can automatically generate usage help to avoid inconsistencies caused by manual updates to use Help.
    • Parameters can be read from different places. When command line arguments do not meet the requirements, you need to use a configuration file or environment variable instead.
      These features are supported and the code churn is minimal.
User Guide
Quick Start
Use the detailed
Multiple sources of parameters

In this section, we start with the simplest examples and learn the usual usage of the Program_options library. The following example is just a snippet of code, and the complete example is in the "Boost_root/libs/program_options/example" directory. For all examples, the assumptions are in the following namespaces:

namespace PO = boost::p rogram_options;
Quick Start

The first example is as simple as possible: It consists of only two parameter items. The code is as follows (see "Example/first.cpp" for the full code):

Declare the supported options.po::options_description desc ("Allowed options");d esc.add_options ()    ("Help", " Produce help Message ")    (" Compression ", Po::value ()," set compression level ");p O::variables_map Vm;po::store (PO:: Parse_command_line (AC, AV, desc), VM);p o::notify (VM);    if (Vm.count ("Help")) {    cout << desc << "\ n";    return 1;} if (Vm.count ("compression")) {    cout << "compression level is set to"  << vm["Compression"].as () < < ". \ n";} else {    cout << "Compression level is not set.\n";}

First, the class options_description describes all allowed parameter items, the class's Add_options method returns a proxy object that defines operator (), calls its operator () to actually describe the parameter item, the function parameter is the parameter item name, the correlation value information, The parameter item description. In this case, the first parameter item has no value, and the second parameter item has a value of type int.

After that, a class Variables_map object is defined. The value used to store the parameter item, which can store any type of value. The store, Parse_command_line, and notify functions are then called, parsing the command-line arguments and saving them to the VM.

Now, you can use the Variables_map class as you would with STD::MAP, but the stored value must be recovered by the at method. If the type specified by the call as method does not match the actual type, an exception is thrown)

Now you can try to compile the code, how to compile the example is as follows:

$bin/gcc/debug/firstcompression level is not set. $bin/gcc/debug/first--helpallowed options:  --help                 : Produce help message  --compression arg      : Set compression Level$bin/gcc/debug/first--compression 10Compression Level is set to 10.    
Use the detailed

The value of the parameter item, in addition to int there are other types, there are other properties that we will discuss below. The complete example is in "Example/options_description.cpp".

Suppose we write a compiler program. It has the most optimized level, including parameters such as multiple paths, multiple input files, and so on. The description parameter entry is as follows:
 

int opt;po::options_description desc ("Allowed options");d esc.add_options ()    ("Help", "produce help message")    ("Optimization", Po::value (&opt)->default_value (Ten),   "optimization level")    ("Include-path,i", po::value< vector > (),   "include path")    ("Input-file", po::value< vector > (), "Input file");

The "--help" item, like the previous precedent, is a good note to have this parameter item in the project.

The "optimization" item embodies two new features. First, we pass the variable (&opt) address, which is used to hold the value of the obtained parameter entry. Then, specify a default value to use when the user does not set a value for this parameter item.
 

The "Include-path" entry illustrates the example of the Options_description class interface only from the command line. The user likes to use the short parameter item name, and the "Include-path,i" name indicates that the short parameter entry name is "I". Therefore, both "--include-path" and "-I" can be used.
 

The "Input-file" parameter entry specifies a list of processing files. There's no problem with writing like this:

Compiler--input-file=a.cpp    

But often this is often the case:

Compiler A.cpp    

Here to explain this usage.

As in the example above, command-line options with no parameter names are called "positional parameters" in this library and can also be processed. The library can explain that "a.cpp" is equivalent to "--input-file=a.cpp". Here is the additional code that is required:

PO::p ositional_options_description p;p.add ("Input-file",-1);p O::variables_map Vm;po::store (po::command_line_ Parser (AC, AV).          Options (DESC). Positional (P). Run (), VM);p o::notify (VM);    

The first two lines indicate that all "positional parameter items" should be translated into "input-file" items. Be careful to parse the command line with the Command_line_parser class instead of the Parse_command_line function. The Parse_command_line function is an encapsulation of the Command_line_parser class for handling simple cases, but now it's time to pass additional information
It's not used.

Now, all parameter entries are described and parsed. We do not implement the rest of the compilation logic, just print the parameters:

if (Vm.count ("Include-path")) {    cout << "Include Paths is:"          << vm["Include-path"].as< vector > () << "\ n";} if (Vm.count ("Input-file")) {    cout << "input files are:"          << vm["input-file"].as< vector > () & lt;< "\ n";} cout << "optimization level is" << opt << "\ n";                

Examples of how to compile are as follows:

$bin/gcc/debug/options_description--helpusage:options_description [options]allowed options:  --help                 : Produce help message  --optimization arg     : Optimization level-I  [--include-path] arg:include path--  I. Nput-file arg       : input file$bin/gcc/debug/options_descriptionoptimization level is 10$bin/gcc/debug/options_ Description--optimization 4-i foo a.cppinclude paths are:fooinput files Are:a.cppoptimization level is 4

Here is a small problem, "help information" requires the designation "--input-file" item name, which will confuse the user. In the following example, you can see how to hide this information.

Multiple sources of parameters

 

It is not realistic to ask the user to specify all parameters to our compiler at the command line. What if the user installs a new library and wants to pass an additional command-line parameter? How do I use this when I want to make a selection run multiple times? You can create a configuration file that organizes command-line arguments together to accomplish this work.

Of course, parsing requires a combination of both command-line parameters and configuration file values. For example, the value of the configuration file is overwritten by the values of the optimization level specified at the command line. On the other hand, the "include path" should contain both the command line and the values in the configuration file.

See the code below. The complete code is in "Examples/multiple_sources.cpp". There are two kinds of details for a parameter item definition. First, you define several instances of the Options_description class. The reason is that, in general, not all parameter item properties are similar. Some items, such as "Input-file" above, should not appear in the automatic Help information. The item only has meaning in the configuration file. Second, it is a good idea to help organize the output of information, not just a long list of parameter items. The following statements declare several sets of parameter items:

Declare A group of options that would be//allowed only on command linepo::options_description generic ("Generic options "); Generic.add_options (    " Version,v "," Print version string ")    (" Help "," produce help Message ")        ;    Declare A group of options that would be//allowed both on command line and in//config filepo::options_description con Fig ("Configuration"); Config.add_options ()    ("Optimization", Po::value (&opt)->default_value (),           " Optimization level ")    (" Include-path,i ",          po::value< vector > ()->composing (),          " Include path ")    ;//Hidden options, 'll be allowed both on command line and//in config file, but would is not is shown to the USER.PO:: Options_description Hidden ("Hidden Options") hidden.add_options (    "Input-file", po::value< vector > (), " Input file ")    ;        

Note the composing method is called in the "Include-path" entry declaration, stating that values from different sources should be merged together, as soon as they are seen below.

The Add method of the Options_description class can be used to further combine parameter items:

Po::options_description cmdline_options;cmdline_options.add (generic). Add (config). Add (hidden);p o::options_ Description Config_file_options;config_file_options.add (config). Add (hidden);p o::options_description visible (" Allowed Options "); Visible.add (generic). Add (config);      

In addition to the extra calls to Parse_config_file and store functions, parameter values are parsed and stored as usual. But when the same parameters are specified in the command line and configuration file, how do I handle them? Typically, the first value that is stored is preferred. This shows how the value of the "--optimization" item is generated. For "Composing" items, like "include-file", values are merged together.

Examples of how to compile are as follows:

$bin/gcc/debug/multiple_sourcesinclude paths is:/optoptimization level is 1$bin/gcc/debug/multiple_sources-- Helpallows options:generic Options:-  v [--version]       : Print version string  --help                 : Produce help message Configuration:  --optimization n       : Optimization level-I  [--include-path] Path:include Path$bin/gcc/debug /multiple_sources--optimization=4-i foo a.cpp b.cppinclude paths are:foo/optinput files Are:a.cpp b.cppoptimization l Evel is 4

Appendix

To enhance understanding, the complete source code mentioned above is listed here.

File Example/first.cpp

 

#include namespace po = boost::p rogram_options; #include #include using namespace std;int main (int AC, char* av[]) {try        {po::options_description desc ("Allowed options"); Desc.add_options () ("Help", "produce help Message") ("Compression", Po::value (), "set compression le        Vel ");                Po::variables_map VMS;        Po::store (PO::p arse_command_line (AC, AV, desc), VM);            Po::notify (VM);            if (Vm.count ("Help")) {cout << desc << "\ n";        return 1;  } if (Vm.count ("compression")) {cout << "compression level is set to" <<        vm["Compression"].as () << ". \ n";        } else {cout << "Compression level is not set.\n";        }} catch (exception& e) {cerr << "error:" << e.what () << "\ n";    return 1; } catch (...)    {Cerr << "Exception of unknown type!\n"; } RETUrn 0;} 

File Example/options_description.cpp

#include using namespace boost;namespace po = boost::p rogram_options, #include #include #include using namespace std;//A h Elper function to simplify the main part.templateostream& operator<< (ostream& os, const vector& v) {C     Opy (V.begin (), V.end (), Ostream_iterator (cout, "")); return OS;}        int main (int AC, char* av[]) {try {int opt;        Po::options_description desc ("Allowed options"); Desc.add_options ("Help", "produce help Message") ("Optimization", Po::value (&opt)->default                   _value (Ten), "Optimization Level") ("Include-path,i", po::value< vector > (),        "Include Path") ("Input-file", po::value< vector > (), "Input file");        PO::p ositional_options_description P;                P.add ("Input-file",-1);        Po::variables_map VMS;                  Po::store (Po::command_line_parser (AC, AV).    Options (DESC). Positional (P). Run (), VM);    Po::notify (VM);            if (Vm.count ("Help")) {cout << "usage:options_description [options]\n";            cout << desc;        return 0; } if (Vm.count ("Include-path")) {cout << "include Paths is:" << V        m["Include-path"].as< vector > () << "\ n"; } if (Vm.count ("Input-file")) {cout << "input files are:" << vm["I        Nput-file "].as< vector > () <<" \ n ";                    } cout << "optimization level is" << opt << "\ n";        } catch (exception& e) {cout << e.what () << "\ n";    return 1; } return 0;}

 

File Examples/multiple_sources.cpp

#include namespace po = boost::p rogram_options; #include #include #include using namespace std;//A helper function to Simp Lify the main part.templateostream& operator<< (ostream& os, const vector& v) {copy (V.begin (), V.end ()     , Ostream_iterator (cout, "")); return OS;}            int main (int AC, char* av[]) {try {int opt; Declare A group of options that would be//allowed with command line po::options_description generic (        "Generic options");                Generic.add_options ("Version,v", "Print version string") ("Help", "produce help Message")            ; Declare A group of options that would be//allowed both on command line and in//config file po:        : options_description config ("Configuration"); Config.add_options ("Optimization", Po::value (&opt)->default_value (Ten), "Optimizatio               N level ") (" Include-path,i ",   po::value< vector > ()->composing (), "include path");        Hidden options, would be is allowed both on command line and//config file, but would is not being shown to the user.        Po::options_description Hidden ("hidden options");                Hidden.add_options () ("Input-file", po::value< vector > (), "Input file");        Po::options_description cmdline_options;        Cmdline_options.add (Generic). Add (config). Add (hidden);        Po::options_description config_file_options;        Config_file_options.add (config). Add (hidden);        Po::options_description visible ("Allowed options");                Visible.add (Generic). Add (config);        PO::p ositional_options_description P;                P.add ("Input-file",-1);        Po::variables_map VMS;              Store (Po::command_line_parser (AC, AV).        Options (cmdline_options). Positional (P). Run (), VM);        Ifstream ifs ("multiple_sources.cfg"); StoreParse_config_file (IFS, config_file_options), VMS);            Notify (VM);            if (Vm.count ("Help")) {cout << visible << "\ n";        return 0;            } if (Vm.count ("version")) {cout << "multiple sources example, version 1.0\n";        return 0; } if (Vm.count ("Include-path")) {cout << "include Paths is:" << V        m["Include-path"].as< vector > () << "\ n"; } if (Vm.count ("Input-file")) {cout << "input files are:" << vm["I        Nput-file "].as< vector > () <<" \ n ";                    } cout << "optimization level is" << opt << "\ n";        } catch (exception& e) {cout << e.what () << "\ n";    return 1; } return 0;}

[c++boost] program parameter Item resolution Library Program_options usage guide

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.