1 <?xml version=
"1.0" standalone=
"yes"?>
2 <!DOCTYPE library PUBLIC
"-//Boost//DTD BoostBook XML V1.0//EN"
3 "http://www.boost.org/tools/boostbook/dtd/boostbook.dtd"
5 <!ENTITY % entities SYSTEM
"program_options.ent" >
8 <section id=
"program_options.howto">
12 <para>This section describes how the library can be used in specific
19 options groups/hidden options
23 <title>Non-conventional Syntax
</title>
25 <para>Sometimes, standard command line syntaxes are not enough. For
26 example, the gcc compiler has
"-frtti" and -fno-rtti
" options, and this
27 syntax is not directly supported.
30 <indexterm><primary>additional parser</primary></indexterm>
31 <para>For such cases, the library allows the user to provide an
32 <firstterm>additional parser</firstterm> -- a function which will be called on each
33 command line element, before any processing by the library. If the
34 additional parser recognises the syntax, it returns the option name and
35 value, which are used directly. The above example can be handled by the
41 pair<string, string> reg_foo(const string& s)
43 if (s.find("-f
") == 0) {
44 if (s.substr(2, 3) == "no-
")
45 return make_pair(s.substr(5), string("false
"));
47 return make_pair(s.substr(2), string("true
"));
49 return make_pair(string(), string());
53 Here's the definition of the additional parser. When parsing the command
54 line, we pass the additional parser:
56 store(command_line_parser(ac, av).options(desc).extra_parser(reg_foo)
59 The complete example can be found in the "example/custom_syntax.cpp
"
65 <title>Response Files</title>
67 <indexterm><primary>response files</primary></indexterm>
69 <para>Some operating system have very low limits of the command line
70 length. The common way to work around those limitations is using
71 <firstterm>response files</firstterm>. A response file is just a
72 configuration file which uses the same syntax as the command line. If
73 the command line specifies a name of response file to use, it's loaded
74 and parsed in addition to the command line. The library does not
75 provide direct support for response files, so you'll need to write some
80 First, you need to define an option for the response file:
82 ("response-file
", value<string>(),
83 "can be specified with '@name', too
")
87 <para>Second, you'll need an additional parser to support the standard syntax
88 for specifying response files: "@file
":
89 <programlisting><![CDATA[
90 pair<string, string> at_option_parser(string const&s)
93 return std::make_pair(string("response-file
"), s.substr(1));
95 return pair<string, string>();
101 <para>Finally, when the "response-file
" option is found, you'll have to
102 load that file and pass it to the command line parser. This part is the
103 hardest. We'll use the Boost.Tokenizer library, which works but has some
104 limitations. You might also consider Boost.StringAlgo. The code is:
105 <programlisting><![CDATA[
106 if (vm.count("response-file
")) {
107 // Load the file and tokenize it
108 ifstream ifs(vm["response-file
"].as<string>().c_str());
110 cout << "Could not open the response file\n
";
113 // Read the whole file into a string
116 // Split the file content
117 char_separator<char> sep(" \n\r
");
118 std::string ResponsefileContents( ss.str() );
119 tokenizer<char_separator<char> > tok(ResponsefileContents, sep);
121 copy(tok.begin(), tok.end(), back_inserter(args));
122 // Parse the file and store the options
123 store(command_line_parser(args).options(desc).run(), vm);
127 The complete example can be found in the "example/response_file.cpp
"
134 <title>Winmain Command Line</title>
136 <para>On the Windows operating system, GUI applications receive the
137 command line as a single string, not split into elements. For that reason,
138 the command line parser cannot be used directly. At least on some
139 compilers, it is possible to obtain
140 the split command line, but it's not clear if all compilers support the
141 same mechanism on all versions of the operating system. The
142 <code>split_winmain</code> function is a portable mechanism provided
143 by the library.</para>
145 <para>Here's an example of use:
147 vector<string> args = split_winmain(lpCmdLine);
148 store(command_line_parser(args).options(desc).run(), vm);
150 The <code>split_winmain</code> function is overloaded for <code>wchar_t</code> strings, so can
151 also be used in Unicode applications.
157 <title>Option Groups and Hidden Options</title>
159 <para>Having a single instance of the &options_description; class with all
160 the program's options can be problematic:
163 <para>Some options make sense only for specific source, for example,
164 configuration files.</para>
167 <para>The user would prefer some structure in the generated help message.</para>
170 <para>Some options shouldn't appear in the generated help message at all.</para>
175 <para>To solve the above issues, the library allows a programmer to create several
176 instances of the &options_description; class, which can be merged in
177 different combinations. The following example will define three groups of
178 options: command line specific, and two options group for specific program
179 modules, only one of which is shown in the generated help message.
182 <para>Each group is defined using standard syntax. However, you should
183 use reasonable names for each &options_description; instance:
184 <programlisting><![CDATA[
185 options_description general("General options
");
186 general.add_options()
187 ("help
", "produce a help message
")
188 ("help-module
", value<string>(),
189 "produce a help for a given module
")
190 ("version
", "output the version number
")
193 options_description gui("GUI options
");
195 ("display
", value<string>(), "display to use
")
198 options_description backend("Backend options
");
199 backend.add_options()
200 ("num-threads
", value<int>(), "the initial number of threads
")
205 <para>After declaring options groups, we merge them in two
206 combinations. The first will include all options and be used for parsing. The
207 second will be used for the "--help
" option.
209 // Declare an options description instance which will include
211 options_description all("Allowed options
");
212 all.add(general).add(gui).add(backend);
214 // Declare an options description instance which will be shown
216 options_description visible("Allowed options
");
217 visible.add(general).add(gui);
221 <para>What is left is to parse and handle the options:
222 <programlisting><![CDATA[
224 store(parse_command_line(ac, av, all), vm);
226 if (vm.count("help
"))
231 if (vm.count("help-module
")) {
232 const string& s = vm["help-module
"].as<string>();
235 } else if (s == "backend
") {
238 cout << "Unknown module '
"
239 << s << "' in the --help-module option\n
";
244 if (vm.count("num-threads
")) {
245 cout << "The 'num-threads' options was set to
"
246 << vm["num-threads
"].as<int>() << "\n
";
249 When parsing the command line, all options are allowed. The "--help
"
250 message, however, does not include the "Backend options
" group -- the
251 options in that group are hidden. The user can explicitly force the
252 display of that options group by passing "--help-module backend
"
253 option. The complete example can be found in the
254 "example/option_groups.cpp
" file.
260 <title>Custom Validators</title>
262 <para>By default, the conversion of option's value from string into C++
263 type is done using iostreams, which sometimes is not convenient. The
264 library allows the user to customize the conversion for specific
265 classes. In order to do so, the user should provide suitable overload of
266 the <code>validate</code> function.
270 Let's first define a simple class:
271 <programlisting><![CDATA[
272 struct magic_number {
274 magic_number(int n) : n(n) {}
277 ]]></programlisting> and then overload the <code>validate</code> function:
278 <programlisting><![CDATA[
279 void validate(boost::any& v,
280 const std::vector<std::string>& values,
281 magic_number* target_type, int)
283 static regex r("\\d\\d\\d-(\\d\\d\\d)
");
285 using namespace boost::program_options;
287 // Make sure no previous assignment to 'a' was made.
288 validators::check_first_occurrence(v);
289 // Extract the first string from 'values'. If there is more than
290 // one string, it's an error, and exception will be thrown.
291 const string& s = validators::get_single_string(values);
293 // Do regex match and convert the interesting part to
296 if (regex_match(s, match, r)) {
297 v = any(magic_number(lexical_cast<int>(match[1])));
299 throw validation_error(validation_error::invalid_option_value);
303 </programlisting>The function takes four parameters. The first is the storage
304 for the value, and in this case is either empty or contains an instance of
305 the <code>magic_number</code> class. The second is the list of strings
306 found in the next occurrence of the option. The remaining two parameters
307 are needed to workaround the lack of partial template specialization and
308 partial function template ordering on some compilers.
311 <para>The function first checks that we don't try to assign to the same
312 option twice. Then it checks that only a single string was passed
313 in. Next the string is verified with the help of the Boost.Regex
314 library. If that test is passed, the parsed value is stored into the
315 <code>v</code> variable.
318 <para>The complete example can be found in the "example/regex.cpp
" file.
325 <title>Unicode Support</title>
327 <para>To use the library with Unicode, you'd need to:
330 <para>Use Unicode-aware parsers for Unicode input</para>
333 <para>Require Unicode support for options which need it</para>
338 <para>Most of the parsers have Unicode versions. For example, the
339 &parse_command_line; function has an overload which takes
340 <code>wchar_t</code> strings, instead of ordinary <code>char</code>.
343 <para>Even if some of the parsers are Unicode-aware, it does not mean you
344 need to change definition of all the options. In fact, for many options,
345 like integer ones, it makes no sense. To make use of Unicode you'll need
346 <emphasis>some</emphasis> Unicode-aware options. They are different from
347 ordinary options in that they accept <code>wstring</code> input, and
348 process it using wide character streams. Creating an Unicode-aware option
349 is easy: just use the the <code>wvalue</code> function instead of the
350 regular <code>value</code>.
353 <para>When an ascii parser passes data to an ascii option, or a Unicode
354 parser passes data to a Unicode option, the data are not changed at
355 all. So, the ascii option will see a string in local 8-bit encoding, and
356 the Unicode option will see whatever string was passed as the Unicode
360 <para>What happens when Unicode data is passed to an ascii option, and
361 vice versa? The library automatically performs the conversion from
362 Unicode to local 8-bit encoding. For example, if command line is in
363 ascii, but you use <code>wstring</code> options, then the ascii input
364 will be converted into Unicode.
367 <para>To perform the conversion, the library uses the <code>codecvt<wchar_t,
368 char></code> locale facet from the global locale. If
369 you want to work with strings that use local 8-bit encoding (as opposed to
370 7-bit ascii subset), your application should start with:
372 locale::global(locale(""));
374 which would set up the conversion facet according to the user's selected
378 <para>It's wise to check the status of the C++ locale support on your
379 implementation, though. The quick test involves three steps:
382 <para>Go the the "test
" directory and build the "test_convert
" binary.</para>
385 <para>Set some non-ascii locale in the environment. On Linux, one can
386 run, for example: <screen>
387 $ export LC_CTYPE=ru_RU.KOI8-R
392 <para>Run the "test_convert
" binary with any non-ascii string in the
393 selected encoding as its parameter. If you see a list of Unicode codepoints,
394 everything's OK. Otherwise, locale support on your system might be
403 <title>Allowing Unknown Options</title>
405 <para>Usually, the library throws an exception on unknown option names. This
406 behaviour can be changed. For example, only some part of your application uses
407 <libraryname>Program_options</libraryname>, and you wish to pass unrecognized options to another part of
408 the program, or even to another application.</para>
410 <para>To allow unregistered options on the command line, you need to use
411 the &basic_command_line_parser; class for parsing (not &parse_command_line;)
412 and call the <methodname alt="boost::program_options::basic_command_line_parser::allow_unregistered
">allow_unregistered</methodname>
413 method of that class:
415 parsed_options parsed =
416 command_line_parser(argc, argv).options(desc).allow_unregistered().run();
419 For each token that looks like an option, but does not have a known name,
420 an instance of &basic_option; will be added to the result.
421 The <code>string_key</code> and <code>value</code> fields of the instance will contain results
422 of syntactic parsing of the token, the <code>unregistered</code> field will be set to <code>true</code>,
423 and the <code>original_tokens</code> field will contain the token as it appeared on the command line.
426 <para>If you want to pass the unrecognized options further, the
427 <functionname alt="boost::program_options::collect_unrecognized
">collect_unrecognized</functionname> function can be used.
428 The function will collect original tokens for all unrecognized values, and optionally, all found positional options.
429 Say, if your code handles a few options, but does not handle positional options at all, you can use the function like this:
431 vector<string> to_pass_further = collect_unrecognized(parsed.options, include_positional);
444 sgml-parent-document: ("userman.xml
" "chapter
")