Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: downloads/boost_1_34_1/doc/html/program_options/tutorial.html @ 29

Last change on this file since 29 was 29, checked in by landauf, 17 years ago

updated boost from 1_33_1 to 1_34_1

File size: 16.1 KB
Line 
1<html>
2<head>
3<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
4<title>Tutorial</title>
5<link rel="stylesheet" href="../boostbook.css" type="text/css">
6<meta name="generator" content="DocBook XSL Stylesheets V1.68.1">
7<link rel="start" href="../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
8<link rel="up" href="../program_options.html" title="Chapter 10. Boost.Program_options">
9<link rel="prev" href="../program_options.html" title="Chapter 10. Boost.Program_options">
10<link rel="next" href="overview.html" title="Library Overview">
11</head>
12<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
13<table cellpadding="2" width="100%">
14<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../boost.png"></td>
15<td align="center"><a href="../../../index.htm">Home</a></td>
16<td align="center"><a href="../../../libs/libraries.htm">Libraries</a></td>
17<td align="center"><a href="../../../people/people.htm">People</a></td>
18<td align="center"><a href="../../../more/faq.htm">FAQ</a></td>
19<td align="center"><a href="../../../more/index.htm">More</a></td>
20</table>
21<hr>
22<div class="spirit-nav">
23<a accesskey="p" href="../program_options.html"><img src="../images/prev.png" alt="Prev"></a><a accesskey="u" href="../program_options.html"><img src="../images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../images/home.png" alt="Home"></a><a accesskey="n" href="overview.html"><img src="../images/next.png" alt="Next"></a>
24</div>
25<div class="section" lang="en">
26<div class="titlepage"><div><div><h2 class="title" style="clear: both">
27<a name="program_options.tutorial"></a>Tutorial</h2></div></div></div>
28<div class="toc"><dl>
29<dt><span class="section"><a href="tutorial.html#id1590784">Getting Started</a></span></dt>
30<dt><span class="section"><a href="tutorial.html#id1590940">Option Details</a></span></dt>
31<dt><span class="section"><a href="tutorial.html#id1591176">Multiple Sources</a></span></dt>
32</dl></div>
33<p>In this section, we'll take a look at the most common usage scenarios
34  of the program_options library, starting with the simplest one. The examples
35  show only the interesting code parts, but the complete programs can be found
36  in the "BOOST_ROOT/libs/program_options/example" directory. Through all the
37  examples, we'll assume that the following namespace alias is in effect:
38</p>
39<pre class="programlisting">namespace po = boost::program_options;</pre>
40<p>
41  </p>
42<div class="section" lang="en">
43<div class="titlepage"><div><div><h3 class="title">
44<a name="id1590784"></a>Getting Started</h3></div></div></div>
45<p>The first example is the simplest possible: it only handles two
46    options. Here's the source code (the full program is in
47    "example/first.cpp"):
48
49</p>
50<pre class="programlisting">
51// Declare the supported options.
52po::options_description desc("Allowed options");
53desc.add_options()
54    ("help", "produce help message")
55    ("compression", po::value&lt;int&gt;(), "set compression level")
56;
57
58po::variables_map vm;
59po::store(po::parse_command_line(ac, av, desc), vm);
60po::notify(vm);   
61
62if (vm.count("help")) {
63    cout &lt;&lt; desc &lt;&lt; "\n";
64    return 1;
65}
66
67if (vm.count("compression")) {
68    cout &lt;&lt; "Compression level was set to "
69 &lt;&lt; vm["compression"].as&lt;int&gt;() &lt;&lt; ".\n";
70} else {
71    cout &lt;&lt; "Compression level was not set.\n";
72}
73</pre>
74<p>
75  </p>
76<p>We start by declaring all allowed options using the
77    <code class="computeroutput"><a href="../boost/program_options/options_description.html" title="Class options_description">options_description</a></code> class. The <code class="computeroutput">add_options</code> method of that
78    class returns a special proxy object that defines
79    <code class="computeroutput">operator()</code>. Calls to that operator actually declare
80    options. The parameters are option name, information about value, and option
81    description. In this example, the first option has no value, and the second
82    one has a value of type <code class="computeroutput">int</code>.
83  </p>
84<p>After that, an object of class <code class="computeroutput">variables_map</code> is
85    declared. That class is intended to store values of options, and can store
86    values of arbitrary types. Next, the calls to <code class="computeroutput">store</code>,
87    <code class="computeroutput">parse_command_line</code> and <code class="computeroutput">notify</code> functions cause
88    <code class="computeroutput">vm</code> to contain all the options found on the command
89    line.</p>
90<p>And now, finally, we can use the options as we like. The
91    <code class="computeroutput">variables_map</code> class can be used just like
92    <code class="computeroutput">std::map</code>, except that values stored there must be retrieved
93    with the <code class="computeroutput">as</code> method shown above. (If the type specified in the
94    call to the <code class="computeroutput">as</code> method is different from the actually stored
95    type, an exception is thrown.)
96  </p>
97<p>It's now a good time to try compiling the code yourself, but if
98    you're not yet ready, here's an example session:
99</p>
100<pre class="screen">
101$<strong class="userinput"><code>bin/gcc/debug/first</code></strong>
102Compression level was not set.
103$<strong class="userinput"><code>bin/gcc/debug/first --help</code></strong>
104Allowed options:
105  --help                 : produce help message
106  --compression arg      : set compression level
107$<strong class="userinput"><code>bin/gcc/debug/first --compression 10</code></strong>
108Compression level was set to 10.
109    </pre>
110<p>
111  </p>
112</div>
113<div class="section" lang="en">
114<div class="titlepage"><div><div><h3 class="title">
115<a name="id1590940"></a>Option Details</h3></div></div></div>
116<p>An option value, surely, can have other types than <code class="computeroutput">int</code>, and
117  can have other interesting properties, which we'll discuss right now. The
118  complete version of the code snipped below can be found in
119  <code class="filename">example/options_description.cpp</code>.</p>
120<p>Imagine we're writing a compiler. It should take the optimization
121    level, a number of include paths, and a number of input files, and perform some
122    interesting work. Let's describe the options:
123    </p>
124<pre class="programlisting">
125int opt;
126po::options_description desc("Allowed options");
127desc.add_options()
128    ("help", "produce help message")
129    ("optimization", po::value&lt;int&gt;(&amp;opt)-&gt;default_value(10),
130  "optimization level")
131    ("include-path,I", po::value&lt; vector&lt;string&gt; &gt;(),
132  "include path")
133    ("input-file", po::value&lt; vector&lt;string&gt; &gt;(), "input file")
134;
135</pre>
136<p>
137  </p>
138<p>The <code class="literal">"help"</code> option should be familiar from
139  the previous example. It's a good idea to have this option in all cases.
140  </p>
141<p>The <code class="literal">"optimization"</code> option shows two new features. First, we specify
142    the address of the variable(<code class="computeroutput">&amp;opt</code>). After storing values, that
143    variable will have the value of the option. Second, we specify a default
144    value of 10, which will be used if no value is specified by the user.
145  </p>
146<p>The <code class="literal">"include-path"</code> option is an example of the
147  only case where the interface of the <code class="computeroutput">options_description</code> 
148  class serves only one
149    source -- the command line. Users typically like to use short option names
150    for common options, and the "include-path,I" name specifies that short
151    option name is "I". So, both "--include-path" and "-I" can be used.
152  </p>
153<p>Note also that the type of the <code class="literal">"include-path"</code>
154  option is <span class="type">std::vector</span>. The library provides special
155  support for vectors -- it will be possible to specify the option several
156  times, and all specified values will be collected in one vector. 
157  </p>
158<p>The "input-file" option specifies the list of files to
159    process. That's okay for a start, but, of course, writing something like:
160    </p>
161<pre class="screen">
162<strong class="userinput"><code>compiler --input-file=a.cpp</code></strong>
163    </pre>
164<p>
165    is a little non-standard, compared with
166    </p>
167<pre class="screen">
168<strong class="userinput"><code>compiler a.cpp</code></strong>
169    </pre>
170<p>
171    We'll address this in a moment.
172  </p>
173<p>
174    The command line tokens which have no option name, as above, are
175    called "positional options" by this library. They can be handled
176    too. With a little help from the user, the library can decide that "a.cpp"
177    really means the same as "--input-file=a.cpp". Here's the additional code
178    we need:
179    </p>
180<pre class="programlisting">
181po::positional_options_description p;
182p.add("input-file", -1);
183
184po::variables_map vm;
185po::store(po::command_line_parser(ac, av).
186          options(desc).positional(p).run(), vm);
187po::notify(vm);
188    </pre>
189<p>   
190  </p>
191<p>
192    The first two lines say that all positional options should be translated
193    into "input-file" options. Also note that we use the
194    <code class="computeroutput">command_line_parser</code> class to parse the command
195    line, not the <code class="computeroutput"><a href="../boost/program_options/parse_command_line.html" title="Function template parse_command_line">parse_command_line</a></code>
196    function. The latter is a convenient wrapper for simple cases, but now we
197    need to pass additional information.
198  </p>
199<p>By now, all options are described and parsed. We'll save ourselves the
200      trouble of implementing the rest of the compiler logic and only print the
201      options:
202    </p>
203<pre class="programlisting">
204if (vm.count("include-path"))
205{
206    cout &lt;&lt; "Include paths are: "
207         &lt;&lt; vm["include-path"].as&lt; vector&lt;string&gt; &gt;() &lt;&lt; "\n";
208}
209
210if (vm.count("input-file"))
211{
212    cout &lt;&lt; "Input files are: "
213         &lt;&lt; vm["input-file"].as&lt; vector&lt;string&gt; &gt;() &lt;&lt; "\n";
214}
215
216cout &lt;&lt; "Optimization level is " &lt;&lt; opt &lt;&lt; "\n";               
217</pre>
218<p>
219  </p>
220<p>Here's an example session:
221    </p>
222<pre class="screen">
223$<strong class="userinput"><code>bin/gcc/debug/options_description --help</code></strong>
224Usage: options_description [options]
225Allowed options:
226  --help                 : produce help message
227  --optimization arg     : optimization level
228  -I [ --include-path ] arg : include path
229  --input-file arg       : input file
230$bin/gcc/debug/options_description
231Optimization level is 10
232$<strong class="userinput"><code>bin/gcc/debug/options_description --optimization 4 -I foo a.cpp</code></strong>
233Include paths are: foo
234Input files are: a.cpp
235Optimization level is 4
236</pre>
237<p>
238  </p>
239<p>
240    Oops, there's a slight problem. It's still possible to specify the
241    "--input-file" option, and usage message says so, which can be confusing
242    for the user. It would be nice to hide this information, but let's wait
243    for the next example.
244  </p>
245</div>
246<div class="section" lang="en">
247<div class="titlepage"><div><div><h3 class="title">
248<a name="id1591176"></a>Multiple Sources</h3></div></div></div>
249<p>It's quite likely that specifying all options to our compiler on the
250    command line will annoy users. What if a user installs a new library and
251    wants to always pass an additional command line element? What if he has
252    made some choices which should be applied on every run? It's desirable to
253    create a config file with common settings which will be used together with
254    the command line.
255    </p>
256<p>Of course, there will be a need to combine the values from command
257    line and config file. For example, the optimization level specified on the
258    command line should override the value from the config file. On the other
259    hand, include paths should be combined.
260    </p>
261<p>Let's see the code now. The complete program is in
262      "examples/multiple_sources.cpp". The option definition has two interesting
263      details. First, we declare several instances of the
264      <code class="computeroutput">options_description</code> class. The reason is that, in general,
265      not all options are alike. Some options, like "input-file" above, should
266      not be presented in an automatic help message. Some options make sense only
267      in the config file. Finally, it's nice to have some structure in the help message,
268      not just a long list of options. Let's declare several option groups:
269      </p>
270<pre class="programlisting">
271// Declare a group of options that will be
272// allowed only on command line
273po::options_description generic("Generic options");
274generic.add_options()
275    ("version,v", "print version string")
276    ("help", "produce help message")   
277    ;
278   
279// Declare a group of options that will be
280// allowed both on command line and in
281// config file
282po::options_description config("Configuration");
283config.add_options()
284    ("optimization", po::value&lt;int&gt;(&amp;opt)-&gt;default_value(10),
285          "optimization level")
286    ("include-path,I",
287         po::value&lt; vector&lt;string&gt; &gt;()-&gt;composing(),
288         "include path")
289    ;
290
291// Hidden options, will be allowed both on command line and
292// in config file, but will not be shown to the user.
293po::options_description hidden("Hidden options");
294hidden.add_options()
295    ("input-file", po::value&lt; vector&lt;string&gt; &gt;(), "input file")
296    ;       
297</pre>
298<p>
299      Note the call to the <code class="computeroutput">composing</code> method in the declaration of the
300      "include-path" option. It tells the library that values from different sources
301      should be composed together, as we'll see shortly.
302    </p>
303<p>   
304      The <code class="computeroutput">add</code> method of the <code class="computeroutput">options_description</code>
305      class can be used to further group the options:
306      </p>
307<pre class="programlisting">
308po::options_description cmdline_options;
309cmdline_options.add(generic).add(config).add(hidden);
310
311po::options_description config_file_options;
312config_file_options.add(config).add(hidden);
313
314po::options_description visible("Allowed options");
315visible.add(generic).add(config);
316      </pre>
317<p>
318    </p>
319<p>The parsing and storing of values follows the usual pattern, except that
320      we additionally call <code class="computeroutput">parse_config_file</code>, and
321      call the <code class="computeroutput"><a href="../id1009524-bb.html" title="Function store">store</a></code> function twice. But what
322      happens if the same value is specified both on the command line and in
323      config file? Usually, the value stored first is preferred. This is what
324      happens for the "--optimization" option. For "composing" options, like
325      "include-file", the values are merged.
326    </p>
327<p>Here's an example session:
328</p>
329<pre class="screen">
330$<strong class="userinput"><code>bin/gcc/debug/multiple_sources</code></strong>
331Include paths are: /opt
332Optimization level is 1
333$<strong class="userinput"><code>bin/gcc/debug/multiple_sources --help</code></strong>
334Allows options:
335
336Generic options:
337  -v [ --version ]       : print version string
338  --help                 : produce help message
339
340Configuration:
341  --optimization n       : optimization level
342  -I [ --include-path ] path : include path
343
344$<strong class="userinput"><code>bin/gcc/debug/multiple_sources --optimization=4 -I foo a.cpp b.cpp</code></strong>
345Include paths are: foo /opt
346Input files are: a.cpp b.cpp
347Optimization level is 4
348</pre>
349<p>
350      The first invocation uses values from the configuration file. The second
351      invocation also uses values from command line. As we see, the include
352      paths on the command line and in the configuration file are merged,
353      while optimization is taken from the command line.
354    </p>
355</div>
356</div>
357<table width="100%"><tr>
358<td align="left"></td>
359<td align="right"><small>Copyright © 2002-2004 Vladimir Prus</small></td>
360</tr></table>
361<hr>
362<div class="spirit-nav">
363<a accesskey="p" href="../program_options.html"><img src="../images/prev.png" alt="Prev"></a><a accesskey="u" href="../program_options.html"><img src="../images/up.png" alt="Up"></a><a accesskey="h" href="../index.html"><img src="../images/home.png" alt="Home"></a><a accesskey="n" href="overview.html"><img src="../images/next.png" alt="Next"></a>
364</div>
365</body>
366</html>
Note: See TracBrowser for help on using the repository browser.