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