1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
2 <html><head><title>CommandLine 2.0 Library Manual</title></head>
5 <table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0>
6 <tr><td> <font size=+3 color="#EEEEFF" face="Georgia,Palatino,Times,Roman"><b>CommandLine 2.0 Library Manual</b></font></td>
10 <li><a href="#introduction">Introduction</a>
11 <li><a href="#quickstart">Quick Start Guide</a>
13 <li><a href="#bool">Boolean Arguments</a>
14 <li><a href="#alias">Argument Aliases</a>
15 <li><a href="#onealternative">Selecting an alternative from a
16 set of possibilities</a>
17 <li><a href="#namedalternatives">Named alternatives</a>
18 <li><a href="#list">Parsing a list of options</a>
19 <li><a href="#description">Adding freeform text to help output</a>
21 <li><a href="#referenceguide">Reference Guide</a>
23 <li><a href="#positional">Positional Arguments</a>
25 <li><a href="#--">Specifying positional options with hyphens</a>
26 <li><a href="#cl::ConsumeAfter">The <tt>cl::ConsumeAfter</tt>
29 <li><a href="#storage">Internal vs External Storage</a>
30 <li><a href="#attributes">Option Attributes</a>
31 <li><a href="#modifiers">Option Modifiers</a>
33 <li><a href="#hiding">Hiding an option from <tt>--help</tt> output</a>
34 <li><a href="#numoccurances">Controlling the number of occurances
35 required and allowed</a>
36 <li><a href="#valrequired">Controlling whether or not a value must be
38 <li><a href="#formatting">Controlling other formatting options</a>
39 <li><a href="#misc">Miscellaneous option modifiers</a>
41 <li><a href="#toplevel">Top-Level Classes and Functions</a>
43 <li><a href="#cl::ParseCommandLineOptions">The
44 <tt>cl::ParseCommandLineOptions</tt> function</a>
45 <li><a href="#cl::ParseEnvironmentOptions">The
46 <tt>cl::ParseEnvironmentOptions</tt> function</a>
47 <li><a href="#cl::opt">The <tt>cl::opt</tt> class</a>
48 <li><a href="#cl::list">The <tt>cl::list</tt> class</a>
49 <li><a href="#cl::alias">The <tt>cl::alias</tt> class</a>
51 <li><a href="#builtinparsers">Builtin parsers</a>
53 <li><a href="#genericparser">The Generic <tt>parser<t></tt>
55 <li><a href="#boolparser">The <tt>parser<bool></tt>
57 <li><a href="#stringparser">The <tt>parser<string></tt>
59 <li><a href="#intparser">The <tt>parser<int></tt>
61 <li><a href="#doubleparser">The <tt>parser<double></tt> and
62 <tt>parser<float></tt> specializations</a>
65 <li><a href="#extensionguide">Extension Guide</a>
67 <li><a href="#customparser">Writing a custom parser</a>
68 <li><a href="#explotingexternal">Exploiting external storage</a>
69 <li><a href="#dynamicopts">Dynamically adding command line options</a>
72 <p><b>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a></b><p>
76 <!-- *********************************************************************** -->
77 <table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0>
78 <tr><td align=center><font color="#EEEEFF" size=+2 face="Georgia,Palatino"><b>
79 <a name="introduction">Introduction
80 </b></font></td></tr></table><ul>
81 <!-- *********************************************************************** -->
83 This document describes the CommandLine argument processing library. It will
84 show you how to use it, and what it can do. The CommandLine library uses a
85 declarative approach to specifying the command line options that your program
86 takes. By default, these options declarations implicitly hold the value parsed
87 for the option declared (of course this <a href="#storage">can be
90 Although there are a <b>lot</b> of command line argument parsing libraries out
91 there in many different languages, none of them fit well with what I needed. By
92 looking at the features and problems of other libraries, I designed the
93 CommandLine library to have the following features:<p>
96 <li>Speed: The CommandLine library is very quick and uses little resources. The
97 parsing time of the library is directly proportional to the number of arguments
98 parsed, not the the number of options recognized. Additionally, command line
99 argument values are captured transparently into user defined global variables,
100 which can be accessed like any other variable (and with the same
103 <li>Type Safe: As a user of CommandLine, you don't have to worry about
104 remembering the type of arguments that you want (is it an int? a string? a
105 bool? an enum?) and keep casting it around. Not only does this help prevent
106 error prone constructs, it also leads to dramatically cleaner source code.<p>
108 <li>No subclasses required: To use CommandLine, you instantiate variables that
109 correspond to the arguments that you would like to capture, you don't subclass a
110 parser. This means that you don't have to write <b>any</b> boilerplate code.<p>
112 <li>Globally accessible: Libraries can specify command line arguments that are
113 automatically enabled in any tool that links to the library. This is possible
114 because the application doesn't have to keep a "list" of arguments to pass to
115 the parser. This also makes supporting <a href="#dynamicopts">dynamically
116 loaded options</a> trivial.<p>
118 <li>Cleaner: CommandLine supports enum and other types directly, meaning that
119 there is less error and more security built into the library. You don't have to
120 worry about whether your integral command line argument accidentally got
121 assigned a value that is not valid for your enum type.<p>
123 <li>Powerful: The CommandLine library supports many different types of
124 arguments, from simple <a href="#boolparser">boolean flags</a> to <a
125 href="#cl::opt">scalars arguments</a> (<a href="#stringparser">strings</a>, <a
126 href="#intparser">integers</a>, <a href="#genericparser">enums</a>, <a
127 href="#doubleparser">doubles</a>), to <a href="#cl::list">lists of
128 arguments</a>. This is possible because CommandLine is...<p>
130 <li>Extensible: It is very simple to add a new argument type to CommandLine.
131 Simply specify the parser that you want to use with the command line option when
132 you declare it. <a href="#customparser">Custom parsers</a> are no problem.<p>
134 <li>Labor Saving: The CommandLine library cuts down on the amount of grunt work
135 that you, the user, have to do. For example, it automatically provides a
136 <tt>--help</tt> option that shows the available command line options for your
137 tool. Additionally, it does most of the basic correctness checking for you.<p>
139 <li>Capable: The CommandLine library can handle lots of different forms of
140 options often found in real programs. For example, <a
141 href="#positional">positional</a> arguments, <tt>ls</tt> style <a
142 href="#cl::Grouping">grouping</a> options (to allow processing '<tt>ls
143 -lad</tt>' naturally), <tt>ld</tt> style <a href="#cl::Prefix">prefix</a>
144 options (to parse '<tt>-lmalloc -L/usr/lib</tt>'), and <a
145 href="#cl::ConsumeAfter">interpreter style options</a>.<p>
149 This document will hopefully let you jump in and start using CommandLine in your
150 utility quickly and painlessly. Additionally it should be a simple reference
151 manual to figure out how stuff works. If it is failing in some area (or you
152 want an extension to the library), nag the author, <a
153 href="mailto:sabre@nondot.org">Chris Lattner</a>.<p>
157 <!-- *********************************************************************** -->
158 </ul><table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0><tr><td align=center><font color="#EEEEFF" size=+2 face="Georgia,Palatino"><b>
159 <a name="quickstart">Quick Start Guide
160 </b></font></td></tr></table><ul>
161 <!-- *********************************************************************** -->
163 This section of the manual runs through a simple CommandLine'ification of a
164 basic compiler tool. This is intended to show you how to jump into using the
165 CommandLine library in your own program, and show you some of the cool things it
168 To start out, you need to include the CommandLine header file into your
172 #include "Support/CommandLine.h"
175 Additionally, you need to add this as the first line of your main program:<p>
178 int main(int argc, char **argv) {
179 <a href="#cl::ParseCommandLineOptions">cl::ParseCommandLineOptions</a>(argc, argv);
184 ... which actually parses the arguments and fills in the variable
187 Now that you are ready to support command line arguments, we need to tell the
188 system which ones we want, and what type of argument they are. The CommandLine
189 library uses a declarative syntax to model command line arguments with the
190 global variable declarations that capture the parsed values. This means that
191 for every command line option that you would like to support, there should be a
192 global variable declaration to capture the result. For example, in a compiler,
193 we would like to support the unix standard '<tt>-o <filename></tt>' option
194 to specify where to put the output. With the CommandLine library, this is
195 represented like this:<p>
197 <pre><a name="value_desc_example">
198 <a href="#cl::opt">cl::opt</a><string> OutputFilename("<i>o</i>", <a href="#cl::desc">cl::desc</a>("<i>Specify output filename</i>"), <a href="#cl::value_desc">cl::value_desc</a>("<i>filename</i>"));
201 This declares a global variable "<tt>OutputFilename</tt>" that is used to
202 capture the result of the "<tt>o</tt>" argument (first parameter). We specify
203 that this is a simple scalar option by using the "<tt><a
204 href="#cl::opt">cl::opt</a></tt>" template (as opposed to the <a
205 href="#list">"<tt>cl::list</tt> template</a>), and tell the CommandLine library
206 that the data type that we are parsing is a string.<p>
208 The second and third parameters (which are optional) are used to specify what to
209 output for the "<tt>--help</tt>" option. In this case, we get a line that looks
213 USAGE: compiler [options]
216 -help - display available options (--help-hidden for more)
217 <b>-o <filename> - Specify output filename</b>
220 Because we specified that the command line option should parse using the
221 <tt>string</tt> data type, the variable declared is automatically usable as a
222 real string in all contexts that a normal C++ string object may be used. For
227 ofstream Output(OutputFilename.c_str());
232 There are many different options that you can use to customize the command line
233 option handling library, but the above example shows the general interface to
234 these options. The options can be specified in any order, and are specified
235 with helper functions like <a href="#cl::desc"><tt>cl::desc(...)</tt></a>, so
236 there are no positional dependencies to remember. The available options are
237 discussed in detail in the <a href="#referenceguide">Reference Guide</a>.<p>
240 Continuing the example, we would like to have our compiler take an input
241 filename as well as an output filename, but we do not want the input filename to
242 be specified with a hyphen (ie, not <tt>-filename.c</tt>). To support this
243 style of argument, the CommandLine library allows for <a
244 href="#positional">positional</a> arguments to be specified for the program.
245 These positional arguments are filled with command line parameters that are not
246 in option form. We use this feature like this:<p>
249 <a href="#cl::opt">cl::opt</a><string> InputFilename(<a href="#cl::Positional">cl::Positional</a>, <a href="#cl::desc">cl::desc</a>("<i><input file></i>"), <a href="#cl::init">cl::init</a>("<i>-</i>"));
252 This declaration indicates that the first positional argument should be treated
253 as the input filename. Here we use the <tt><a
254 href="#cl::init">cl::init</a></tt> option to specify an initial value for the
255 command line option, which is used if the option is not specified (if you do not
256 specify a <tt><a href="#cl::init">cl::init</a></tt> modifier for an option, then
257 the default constructor for the data type is used to initialize the value).
258 Command line options default to being optional, so if we would like to require
259 that the user always specify an input filename, we would add the <tt><a
260 href="#cl::Required">cl::Required</a></tt> flag, and we could eliminate the
261 <tt><a href="#cl::init">cl::init</a></tt> modifier, like this:<p>
264 <a href="#cl::opt">cl::opt</a><string> InputFilename(<a href="#cl::Positional">cl::Positional</a>, <a href="#cl::desc">cl::desc</a>("<i><input file></i>"), <b><a href="#cl::Required">cl::Required</a></b>);
267 Again, the CommandLine library does not require the options to be specified in
268 any particular order, so the above declaration is equivalent to:<p>
271 <a href="#cl::opt">cl::opt</a><string> InputFilename(<a href="#cl::Positional">cl::Positional</a>, <a href="#cl::Required">cl::Required</a>, <a href="#cl::desc">cl::desc</a>("<i><input file></i>"));
274 By simply adding the <tt><a href="#cl::Required">cl::Required</a></tt> flag, the
275 CommandLine library will automatically issue an error if the argument is not
276 specified, which shifts all of the command line option verification code out of
277 your application into the library. This is just one example of how using flags
278 can alter the default behaviour of the library, on a per-option basis. By
279 adding one of the declarations above, the <tt>--help</tt> option synopsis is now
283 USAGE: compiler [options] <b><input file></b>
286 -help - display available options (--help-hidden for more)
287 -o <filename> - Specify output filename
290 ... indicating that an input filename is expected.<p>
294 <!-- ======================================================================= -->
295 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0><tr><td> </td><td width="100%"> <font color="#EEEEFF" face="Georgia,Palatino"><b>
296 <a name="bool">Boolean Arguments
297 </b></font></td></tr></table><ul>
299 In addition to input and output filenames, we would like the compiler example to
300 support three boolean flags: "<tt>-f</tt>" to force overwriting of the output
301 file, "<tt>--quiet</tt>" to enable quiet mode, and "<tt>-q</tt>" for backwards
302 compatibility with some of our users. We can support these by declaring options
303 of boolean type like this:<p>
306 <a href="#cl::opt">cl::opt</a><bool> Force ("<i>f</i>", <a href="#cl::desc">cl::desc</a>("<i>Overwrite output files</i>"));
307 <a href="#cl::opt">cl::opt</a><bool> Quiet ("<i>quiet</i>", <a href="#cl::desc">cl::desc</a>("<i>Don't print informational messages</i>"));
308 <a href="#cl::opt">cl::opt</a><bool> Quiet2("<i>q</i>", <a href="#cl::desc">cl::desc</a>("<i>Don't print informational messages</i>"), <a href="#cl::Hidden">cl::Hidden</a>);
311 This does what you would expect: it declares three boolean variables
312 ("<tt>Force</tt>", "<tt>Quiet</tt>", and "<tt>Quiet2</tt>") to recognize these
313 options. Note that the "<tt>-q</tt>" option is specified with the "<a
314 href="#cl::Hidden"><tt>cl::Hidden</tt></a>" flag. This modifier prevents it
315 from being shown by the standard "<tt>--help</tt>" output (note that it is still
316 shown in the "<tt>--help-hidden</tt>" output).<p>
318 The CommandLine library uses a <a href="#builtinparsers">different parser</a>
319 for different data types. For example, in the string case, the argument passed
320 to the option is copied literally into the content of the string variable... we
321 obviously cannot do that in the boolean case, however, so we must use a smarter
322 parser. In the case of the boolean parser, it allows no options (in which case
323 it assigns the value of true to the variable), or it allows the values
324 "<tt>true</tt>" or "<tt>false</tt>" to be specified, allowing any of the
328 compiler -f # No value, 'Force' == true
329 compiler -f=true # Value specified, 'Force' == true
330 compiler -f=TRUE # Value specified, 'Force' == true
331 compiler -f=FALSE # Value specified, 'Force' == false
334 ... you get the idea. The <a href="#boolparser">bool parser</a> just turns the
335 string values into boolean values, and rejects things like '<tt>compiler
336 -f=foo</tt>'. Similarly, the <a href="#doubleparser">float</a>, <a
337 href="#doubleparser">double</a>, and <a href="#intparser">int</a> parsers work
338 like you would expect, using the '<tt>strtol</tt>' and '<tt>strtod</tt>' C
339 library calls to parse the string value into the specified data type.<p>
341 With the declarations above, "<tt>compiler --help</tt>" emits this:<p>
344 USAGE: compiler [options] <input file>
347 <b>-f - Overwrite output files</b>
348 -o - Override output filename
349 <b>-quiet - Don't print informational messages</b>
350 -help - display available options (--help-hidden for more)
353 and "<tt>opt --help-hidden</tt>" prints this:<p>
356 USAGE: compiler [options] <input file>
359 -f - Overwrite output files
360 -o - Override output filename
361 <b>-q - Don't print informational messages</b>
362 -quiet - Don't print informational messages
363 -help - display available options (--help-hidden for more)
366 This brief example has shown you how to use the '<tt><a
367 href="#cl::opt">cl::opt</a></tt>' class to parse simple scalar command line
368 arguments. In addition to simple scalar arguments, the CommandLine library also
369 provides primitives to support CommandLine option <a href="#alias">aliases</a>,
370 and <a href="#list">lists</a> of options.<p>
373 <!-- ======================================================================= -->
374 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0><tr><td> </td><td width="100%"> <font color="#EEEEFF" face="Georgia,Palatino"><b>
375 <a name="alias">Argument Aliases
376 </b></font></td></tr></table><ul>
378 So far, the example works well, except for the fact that we need to check the
379 quiet condition like this now:<p>
383 if (!Quiet && !Quiet2) printInformationalMessage(...);
387 ... which is a real pain! Instead of defining two values for the same
388 condition, we can use the "<tt><a href="#cl::alias">cl::alias</a></tt>" class to make the "<tt>-q</tt>"
389 option an <b>alias</b> for the "<tt>-quiet</tt>" option, instead of providing
393 <a href="#cl::opt">cl::opt</a><bool> Force ("<i>f</i>", <a href="#cl::desc">cl::desc</a>("<i>Overwrite output files</i>"));
394 <a href="#cl::opt">cl::opt</a><bool> Quiet ("<i>quiet</i>", <a href="#cl::desc">cl::desc</a>("<i>Don't print informational messages</i>"));
395 <a href="#cl::alias">cl::alias</a> QuietA("<i>q</i>", <a href="#cl::desc">cl::desc</a>("<i>Alias for -quiet</i>"), <a href="#cl::aliasopt">cl::aliasopt</a>(Quiet));
398 The third line (which is the only one we modified from above) defines a
399 "<tt>-q</tt> alias that updates the "<tt>Quiet</tt>" variable (as specified by
400 the <tt><a href="#cl::aliasopt">cl::aliasopt</a></tt> modifier) whenever it is
401 specified. Because aliases do not hold state, the only thing the program has to
402 query is the <tt>Quiet</tt> variable now. Another nice feature of aliases is
403 that they automatically hide themselves from the <tt>-help</tt> output
404 (although, again, they are still visible in the <tt>--help-hidden
407 Now the application code can simply use:<p>
411 if (!Quiet) printInformationalMessage(...);
415 ... which is much nicer! The "<tt><a href="#cl::alias">cl::alias</a></tt>" can be used to specify an
416 alternative name for any variable type, and has many uses.<p>
420 <!-- ======================================================================= -->
421 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0><tr><td> </td><td width="100%"> <font color="#EEEEFF" face="Georgia,Palatino"><b>
422 <a name="onealternative">Selecting an alternative from a set of possibilities
423 </b></font></td></tr></table><ul>
425 So far, we have seen how the CommandLine library handles builtin types like
426 <tt>std::string</tt>, <tt>bool</tt> and <tt>int</tt>, but how does it handle
427 things it doesn't know about, like enums or '<tt>int*</tt>'s?<p>
429 The answer is that it uses a table driven generic parser (unless you specify
430 your own parser, as described in the <a href="#extensionguide">Extension
431 Guide</a>). This parser maps literal strings to whatever type is required, are
432 requires you to tell it what this mapping should be.<p>
434 Lets say that we would like to add four optimizations levels to our optimizer,
435 using the standard flags "<tt>-g</tt>", "<tt>-O0</tt>", "<tt>-O1</tt>", and
436 "<tt>-O2</tt>". We could easily implement this with boolean options like above,
437 but there are several problems with this strategy:<p>
440 <li>A user could specify more than one of the options at a time, for example,
441 "<tt>opt -O3 -O2</tt>". The CommandLine library would not be able to catch this
442 erroneous input for us.
444 <li>We would have to test 4 different variables to see which ones are set.
446 <li>This doesn't map to the numeric levels that we want... so we cannot easily
447 see if some level >= "<tt>-O1</tt>" is enabled.
451 To cope with these problems, we can use an enum value, and have the CommandLine
452 library fill it in with the appropriate level directly, which is used like
460 <a href="#cl::opt">cl::opt</a><OptLevel> OptimizationLevel(<a href="#cl::desc">cl::desc</a>("<i>Choose optimization level:</i>"),
461 <a href="#cl::values">cl::values</a>(
462 clEnumVal(g , "<i>No optimizations, enable debugging</i>"),
463 clEnumVal(O1, "<i>Enable trivial optimizations</i>"),
464 clEnumVal(O2, "<i>Enable default optimizations</i>"),
465 clEnumVal(O3, "<i>Enable expensive optimizations</i>"),
469 if (OptimizationLevel >= O2) doPartialRedundancyElimination(...);
473 This declaration defines a variable "<tt>OptimizationLevel</tt>" of the
474 "<tt>OptLevel</tt>" enum type. This variable can be assigned any of the values
475 that are listed in the declaration (Note that the declaration list must be
476 terminated with the "<tt>0</tt>" argument!). The CommandLine library enforces
477 that the user can only specify one of the options, and it ensure that only valid
478 enum values can be specified. The "<tt>clEnumVal</tt>" macros ensure that the
479 command line arguments matched the enum values. With this option added, our
480 help output now is:<p>
483 USAGE: compiler [options] <input file>
486 <b>Choose optimization level:
487 -g - No optimizations, enable debugging
488 -O1 - Enable trivial optimizations
489 -O2 - Enable default optimizations
490 -O3 - Enable expensive optimizations</b>
491 -f - Overwrite output files
492 -help - display available options (--help-hidden for more)
493 -o <filename> - Specify output filename
494 -quiet - Don't print informational messages
497 In this case, it is sort of awkward that flag names correspond directly to enum
498 names, because we probably don't want a enum definition named "<tt>g</tt>" in
499 our program. Because of this, we can alternatively write this example like
507 <a href="#cl::opt">cl::opt</a><OptLevel> OptimizationLevel(<a href="#cl::desc">cl::desc</a>("<i>Choose optimization level:</i>"),
508 <a href="#cl::values">cl::values</a>(
509 clEnumValN(Debug, "g", "<i>No optimizations, enable debugging</i>"),
510 clEnumVal(O1 , "<i>Enable trivial optimizations</i>"),
511 clEnumVal(O2 , "<i>Enable default optimizations</i>"),
512 clEnumVal(O3 , "<i>Enable expensive optimizations</i>"),
516 if (OptimizationLevel == Debug) outputDebugInfo(...);
520 By using the "<tt>clEnumValN</tt>" macro instead of "<tt>clEnumVal</tt>", we can
521 directly specify the name that the flag should get. In general a direct mapping
522 is nice, but sometimes you can't or don't want to preserve the mapping, which is
523 when you would use it.<p>
527 <!-- ======================================================================= -->
528 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0><tr><td> </td><td width="100%"> <font color="#EEEEFF" face="Georgia,Palatino"><b>
529 <a name="namedalternatives">Named Alternatives
530 </b></font></td></tr></table><ul>
532 Another useful argument form is a named alternative style. We shall use this
533 style in our compiler to specify different debug levels that can be used.
534 Instead of each debug level being its own switch, we want to support the
535 following options, of which only one can be specified at a time:
536 "<tt>--debug-level=none</tt>", "<tt>--debug-level=quick</tt>",
537 "<tt>--debug-level=detailed</tt>". To do this, we use the exact same format as
538 our optimization level flags, but we also specify an option name. For this
539 case, the code looks like this:<p>
543 nodebuginfo, quick, detailed
546 // Enable Debug Options to be specified on the command line
547 <a href="#cl::opt">cl::opt</a><DebugLev> DebugLevel("<i>debug_level</i>", <a href="#cl::desc">cl::desc</a>("<i>Set the debugging level:</i>"),
548 <a href="#cl::values">cl::values</a>(
549 clEnumValN(nodebuginfo, "none", "<i>disable debug information</i>"),
550 clEnumVal(quick, "<i>enable quick debug information</i>"),
551 clEnumVal(detailed, "<i>enable detailed debug information</i>"),
555 This definition defines an enumerated command line variable of type "<tt>enum
556 DebugLev</tt>", which works exactly the same way as before. The difference here
557 is just the interface exposed to the user of your program and the help output by
558 the "<tt>--help</tt>" option:<p>
561 USAGE: compiler [options] <input file>
564 Choose optimization level:
565 -g - No optimizations, enable debugging
566 -O1 - Enable trivial optimizations
567 -O2 - Enable default optimizations
568 -O3 - Enable expensive optimizations
569 <b>-debug_level - Set the debugging level:
570 =none - disable debug information
571 =quick - enable quick debug information
572 =detailed - enable detailed debug information</b>
573 -f - Overwrite output files
574 -help - display available options (--help-hidden for more)
575 -o <filename> - Specify output filename
576 -quiet - Don't print informational messages
579 Again, the only structural difference between the debug level declaration and
580 the optimiation level declaration is that the debug level declaration includes
581 an option name (<tt>"debug_level"</tt>), which automatically changes how the
582 library processes the argument. The CommandLine library supports both forms so
583 that you can choose the form most appropriate for your application.<p>
587 <!-- ======================================================================= -->
588 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0><tr><td> </td><td width="100%"> <font color="#EEEEFF" face="Georgia,Palatino"><b>
589 <a name="list">Parsing a list of options
590 </b></font></td></tr></table><ul>
592 Now that we have the standard run of the mill argument types out of the way,
593 lets get a little wild and crazy. Lets say that we want our optimizer to accept
594 a <b>list</b> of optimizations to perform, allowing duplicates. For example, we
595 might want to run: "<tt>compiler -dce -constprop -inline -dce -strip</tt>". In
596 this case, the order of the arguments and the number of appearances is very
597 important. This is what the "<tt><a href="#cl::list">cl::list</a></tt>"
598 template is for. First, start by defining an enum of the optimizations that you
599 would like to perform:<p>
603 // 'inline' is a C++ keyword, so name it 'inlining'
604 dce, constprop, inlining, strip
608 Then define your "<tt><a href="#cl::list">cl::list</a></tt>" variable:<p>
611 <a href="#cl::list">cl::list</a><Opts> OptimizationList(<a href="#cl::desc">cl::desc</a>("<i>Available Optimizations:</i>"),
612 <a href="#cl::values">cl::values</a>(
613 clEnumVal(dce , "<i>Dead Code Elimination</i>"),
614 clEnumVal(constprop , "<i>Constant Propagation</i>"),
615 clEnumValN(inlining, "<i>inline</i>", "<i>Procedure Integration</i>"),
616 clEnumVal(strip , "<i>Strip Symbols</i>"),
620 This defines a variable that is conceptually of the type
621 "<tt>std::vector<enum Opts></tt>". Thus, you can access it with standard
625 for (unsigned i = 0; i != OptimizationList.size(); ++i)
626 switch (OptimizationList[i])
630 ... to iterate through the list of options specified.<p>
632 Note that the "<tt><a href="#cl::list">cl::list</a></tt>" template is completely general and may be used
633 with any data types or other arguments that you can use with the
634 "<tt><a href="#cl::opt">cl::opt</a></tt>" template. One especially useful way to use a list is to
635 capture all of the positional arguments together if there may be more than one
636 specified. In the case of a linker, for example, the linker takes several
637 '<tt>.o</tt>' files, and needs to capture them into a list. This is naturally
642 <a href="#cl::list">cl::list</a><std::string> InputFilenames(<a href="#cl::Positional">cl::Positional</a>, <a href="#cl::desc">cl::desc</a>("<Input files>"), <a href="#cl::OneOrMore">cl::OneOrMore</a>);
646 This variable works just like a "<tt>vector<string></tt>" object. As
647 such, accessing the list is simple, just like above. In this example, we used
648 the <tt><a href="#cl::OneOrMore">cl::OneOrMore</a></tt> modifier to inform the
649 CommandLine library that it is an error if the user does not specify any
650 <tt>.o</tt> files on our command line. Again, this just reduces the amount of
651 checking we have to do.<p>
655 <!-- ======================================================================= -->
656 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0><tr><td> </td><td width="100%"> <font color="#EEEEFF" face="Georgia,Palatino"><b>
657 <a name="description">Adding freeform text to help output
658 </b></font></td></tr></table><ul>
660 As our program grows and becomes more mature, we may decide to put summary
661 information about what it does into the help output. The help output is styled
662 to look similar to a Unix <tt>man</tt> page, providing concise information about
663 a program. Unix <tt>man</tt> pages, however often have a description about what
664 the program does. To add this to your CommandLine program, simply pass a third
666 href="#cl::ParseCommandLineOptions"><tt>cl::ParseCommandLineOptions</tt></a>
667 call in main. This additional argument is then printed as the overview
668 information for your program, allowing you to include any additional information
669 that you want. For example:<p>
672 int main(int argc, char **argv) {
673 <a href="#cl::ParseCommandLineOptions">cl::ParseCommandLineOptions</a>(argc, argv, " CommandLine compiler example\n\n"
674 " This program blah blah blah...\n");
679 Would yield the help output:
682 <b>OVERVIEW: CommandLine compiler example
684 This program blah blah blah...</b>
686 USAGE: compiler [options] <input file>
690 -help - display available options (--help-hidden for more)
691 -o <filename> - Specify output filename
697 <!-- *********************************************************************** -->
698 </ul><table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0><tr><td align=center><font color="#EEEEFF" size=+2 face="Georgia,Palatino"><b>
699 <a name="referenceguide">Reference Guide
700 </b></font></td></tr></table><ul>
701 <!-- *********************************************************************** -->
703 Now that you know the basics of how to use the CommandLine library, this section
704 will give you the detailed information you need to tune how command line options
705 work, as well as information on more "advanced" command line option processing
709 <!-- ======================================================================= -->
710 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0><tr><td> </td><td width="100%"> <font color="#EEEEFF" face="Georgia,Palatino"><b>
711 <a name="positional">Positional Arguments
712 </b></font></td></tr></table><ul>
714 Positional arguments are those arguments that are not named, and are not
715 specified with a hyphen. Positional arguments should be used when an option is
716 specified by its position alone. For example, the standard Unix <tt>grep</tt>
717 tool takes a regular expression argument, and an optional filename to search
718 through (which defaults to standard input if a filename is not specified).
719 Using the CommandLine library, this would be specified as:<p>
722 <a href="#cl::opt">cl::opt</a><string> Regex (<a href="#cl::Positional">cl::Positional</a>, <a href="#cl::desc">cl::desc</a>("<i><regular expression></i>"), <a href="#cl::Required">cl::Required</a>);
723 <a href="#cl::opt">cl::opt</a><string> Filename(<a href="#cl::Positional">cl::Positional</a>, <a href="#cl::desc">cl::desc</a>("<i><input file></i>"), <a href="#cl::init">cl::init</a>("<i>-</i>"));
726 Given these two option declarations, the <tt>--help</tt> output for our grep
727 replacement would look like this:<p>
730 USAGE: spiffygrep [options] <b><regular expression> <input file></b>
733 -help - display available options (--help-hidden for more)
736 ... and the resultant program could be used just like the standard <tt>grep</tt>
739 Positional arguments are sorted by their order of construction. This means that
740 command line options will be ordered according to how they are listed in a .cpp
741 file, but will not have an ordering defined if they positional arguments are
742 defined in multiple .cpp files. The fix for this problem is simply to define
743 all of your positional arguments in one .cpp file.<p>
747 <!-- _______________________________________________________________________ -->
748 </ul><a name="--"><h4><hr size=0>Specifying positional options with hyphens</h4><ul>
750 Sometimes you may want to specify a value to your positional argument that
751 starts with a hyphen (for example, searching for '<tt>-foo</tt>' in a file). At
752 first, you will have trouble doing this, because it will try to find an argument
753 named '<tt>-foo</tt>', and will fail (and single quotes will not save you).
754 Note that the system <tt>grep</tt> has the same problem:<p>
757 $ spiffygrep '-foo' test.txt
758 Unknown command line argument '-foo'. Try: spiffygrep --help'
760 $ grep '-foo' test.txt
761 grep: illegal option -- f
762 grep: illegal option -- o
763 grep: illegal option -- o
764 Usage: grep -hblcnsviw pattern file . . .
767 The solution for this problem is the same for both your tool and the system
768 version: use the '<tt>--</tt>' marker. When the user specifies '<tt>--</tt>' on
769 the command line, it is telling the program that all options after the
770 '<tt>--</tt>' should be treated as positional arguments, not options. Thus, we
771 can use it like this:<p>
774 $ spiffygrep -- -foo test.txt
780 <!-- _______________________________________________________________________ -->
781 </ul><a name="cl::ConsumeAfter"><h4><hr size=0>The <tt>cl::ConsumeAfter</tt> modifier</h4><ul>
783 The <tt>cl::ConsumeAfter</tt> <a href="#formatting">formatting option</a> is
784 used to construct programs that use "interpreter style" option processing. With
785 this style of option processing, all arguments specified after the last
786 positional argument are treated as special interpreter arguments that are not
787 interpreted by the command line argument.<p>
789 As a concrete example, lets say we are developing a replacement for the standard
790 Unix Bourne shell (<tt>/bin/sh</tt>). To run <tt>/bin/sh</tt>, first you
791 specify options to the shell itself (like <tt>-x</tt> which turns on trace
792 output), then you specify the name of the script to run, then you specify
793 arguments to the script. These arguments to the script are parsed by the bourne
794 shell command line option processor, but are not interpreted as options to the
795 shell itself. Using the CommandLine library, we would specify this as:<p>
798 <a href="#cl::opt">cl::opt</a><string> Script(<a href="#cl::Positional">cl::Positional</a>, <a href="#cl::desc">cl::desc</a>("<i><input script></i>"), <a href="#cl::init">cl::init</a>("-"));
799 <a href="#cl::list">cl::list</a><string> Argv(<a href="#cl::ConsumeAfter">cl::ConsumeAfter</a>, <a href="#cl::desc">cl::desc</a>("<i><program arguments>...</i>"));
800 <a href="#cl::opt">cl::opt</a><bool> Trace("<i>x</i>", <a href="#cl::desc">cl::desc</a>("<i>Enable trace output</i>"));
803 which automatically provides the help output:<p>
806 USAGE: spiffysh [options] <b><input script> <program arguments>...</b>
809 -help - display available options (--help-hidden for more)
810 <b>-x - Enable trace output</b>
813 At runtime, if we run our new shell replacement as '<tt>spiffysh -x test.sh -a
814 -x -y bar</tt>', the <tt>Trace</tt> variable will be set to true, the
815 <tt>Script</tt> variable will be set to "<tt>test.sh</tt>", and the
816 <tt>Argv</tt> list will contain <tt>["-a", "-x", "-y", "bar"]</tt>, because
817 they were specified after the last positional argument (which is the script
820 There are several limitations to when <tt>cl::ConsumeAfter</tt> options can be
821 specified. For example, only one <tt>cl::ConsumeAfter</tt> can be specified per
822 program, there must be at least one <a href="#positional">positional
823 argument</a> specified, and the <tt>cl::ConsumeAfter</tt> option should be a <a
824 href="#cl::list">cl::list</a> option.<p>
828 <!-- ======================================================================= -->
829 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0><tr><td> </td><td width="100%"> <font color="#EEEEFF" face="Georgia,Palatino"><b>
830 <a name="storage">Internal vs External Storage
831 </b></font></td></tr></table><ul>
833 By default, all command line options automatically hold the value that they
834 parse from the command line. This is very convenient in the common case,
835 especially when combined with the ability to define command line options in the
836 files that use them. This is called the internal storage model.<p>
838 Sometimes, however, it is nice to separate the command line option processing
839 code from the storage of the value parsed. For example, lets say that we have a
840 '<tt>-debug</tt>' option that we would like to use to enable debug information
841 across the entire body of our program. In this case, the boolean value
842 controlling the debug code should be globally accessable (in a header file, for
843 example) yet the command line option processing code should not be exposed to
844 all of these clients (requiring lots of .cpp files to #include
845 <tt>CommandLine.h</tt>).<p>
847 To do this, set up your .h file with your option, like this for example:<p>
850 <i>// DebugFlag.h - Get access to the '-debug' command line option
853 // DebugFlag - This boolean is set to true if the '-debug' command line option
854 // is specified. This should probably not be referenced directly, instead, use
855 // the DEBUG macro below.
857 extern bool DebugFlag;
859 <i>// DEBUG macro - This macro should be used by code to emit debug information.
860 // In the '-debug' option is specified on the command line, and if this is a
861 // debug build, then the code specified as the option to the macro will be
862 // executed. Otherwise it will not be. Example:
864 // DEBUG(cerr << "Bitset contains: " << Bitset << "\n");
866 <font color=red>#ifdef NDEBUG
869 #define DEBUG(X)</font> \
870 do { if (DebugFlag) { X; } } while (0)
871 <font color=red>#endif</font>
874 This allows clients to blissfully use the <tt>DEBUG()</tt> macro, or the
875 <tt>DebugFlag</tt> explicitly if they want to. Now we just need to be able to
876 set the <tt>DebugFlag</tt> boolean when the option is set. To do this, we pass
877 an additial argument to our command line argument processor, and we specify
878 where to fill in with the <a href="#cl::location">cl::location</a> attribute:<p>
881 bool DebugFlag; <i>// the actual value</i>
882 static <a href="#cl::opt">cl::opt</a><bool, true> <i>// The parser</i>
883 Debug("<i>debug</i>", <a href="#cl::desc">cl::desc</a>("<i>Enable debug output</i>")</a>, <a href="#cl::Hidden">cl::Hidden</a>,
884 <a href="#cl::location">cl::location</a>(DebugFlag));
887 In the above example, we specify "<tt>true</tt>" as the second argument to the
888 <a href="#cl::opt">cl::opt</a> template, indicating that the template should not
889 maintain a copy of the value itself. In addition to this, we specify the <a
890 href="#cl::location">cl::location</a> attribute, so that <tt>DebugFlag</tt> is
891 automatically set.<p>
895 <!-- ======================================================================= -->
896 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0><tr><td> </td><td width="100%"> <font color="#EEEEFF" face="Georgia,Palatino"><b>
897 <a name="attributes">Option Attributes
898 </b></font></td></tr></table><ul>
900 This section describes the basic attributes that you can specify on options.<p>
904 <li>The option name attribute (which is required for all options, except <a
905 href="#positional">positional options</a>) specifies what the option name is.
906 This option is specified in simple double quotes:<p>
909 <a href="#cl::opt">cl::opt</a><<b>bool</b>> Quiet("<i>quiet</i>");
912 <li><a name="cl::desc">The <b><tt>cl::desc</tt></b> attribute specifies a
913 description for the option to be shown in the <tt>--help</tt> output for the
916 <li><a name="cl::value_desc">The <b><tt>cl::value_desc</tt></b> attribute
917 specifies a string that can be used to fine tune the <tt>--help</tt> output for
918 a command line option. Look <a href="#value_desc_example">here</a> for an
921 <li><a name="cl::init">The <b><tt>cl::init</tt></b> attribute specifies an
922 inital value for a <a href="#cl::opt">scalar</a> option. If this attribute is
923 not specified then the command line option value defaults to the value created
924 by the default constructor for the type. <b>Warning</b>: If you specify both
925 <b><tt>cl::init</tt></b> and <b><tt>cl::location</tt></b> for an option,
926 you must specify <b><tt>cl::location</tt></b> first, so that when the
927 command-line parser sees <b><tt>cl::init</tt></b>, it knows where to put the
928 initial value. (You will get an error at runtime if you don't put them in
931 <li><a name="cl::location">The <b><tt>cl::location</tt></b> attribute where to
932 store the value for a parsed command line option if using external storage. See
933 the section on <a href="#storage">Internal vs External Storage</a> for more
936 <li><a name="cl::aliasopt">The <b><tt>cl::aliasopt</tt></b> attribute specifies
937 which option a <a href="#cl::alias">cl::alias</a> option is an alias for.<p>
939 <li><a name="cl::values">The <b><tt>cl::values</tt></b> attribute specifies the
940 string-to-value mapping to be used by the generic parser. It takes a <b>null
941 terminated</b> list of (option, value, description) triplets that specify the
942 option name, the value mapped to, and the description shown in the
943 <tt>--help</tt> for the tool. Because the generic parser is used most frequently with enum values, two macros are often useful:<p>
945 <li><a name="clEnumVal">The <b><tt>clEnumVal</tt></b> macro is used as a nice
946 simple way to specify a triplet for an enum. This macro automatically makes the
947 option name be the same as the enum name. The first option to the macro is the
948 enum, the second is the description for the command line option.<p> <li><a
949 name="clEnumValN">The <b><tt>clEnumValN</tt></b> macro is used to specify macro
950 options where the option name doesn't equal the enum name. For this macro, the
951 first argument is the enum value, the second is the flag name, and the second is
955 You will get a compile time error if you try to use cl::values with a parser
956 that does not support it.<p>
962 <!-- ======================================================================= -->
963 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0><tr><td> </td><td width="100%"> <font color="#EEEEFF" face="Georgia,Palatino"><b>
964 <a name="modifiers">Option Modifiers
965 </b></font></td></tr></table><ul>
967 Option modifiers are the flags and expressions that you pass into the
968 constructors for <tt><a href="#cl::opt">cl::opt</a></tt> and <tt><a
969 href="#cl::list">cl::list</a></tt>. These modifiers give you the ability to
970 tweak how options are parsed and how <tt>--help</tt> output is generated to fit
971 your application well.<p>
973 These options fall into five main catagories:<p>
976 <li><a href="#hiding">Hiding an option from <tt>--help</tt> output</a>
977 <li><a href="#numoccurances">Controlling the number of occurances
978 required and allowed</a>
979 <li><a href="#valrequired">Controlling whether or not a value must be
981 <li><a href="#formatting">Controlling other formatting options</a>
982 <li><a href="#misc">Miscellaneous option modifiers</a>
985 It is not possible to specify two options from the same catagory (you'll get a
986 runtime error) to a single option, except for options in the miscellaneous
987 catagory. The CommandLine library specifies defaults for all of these settings
988 that are the most useful in practice and the most common, which mean that you
989 usually shouldn't have to worry about these.<p>
992 <!-- _______________________________________________________________________ -->
993 </ul><a name="hiding"><h4><hr size=0>Hiding an option from <tt>--help</tt> output</h4><ul>
995 The <tt>cl::NotHidden</tt>, <tt>cl::Hidden</tt>, and <tt>cl::ReallyHidden</tt>
996 modifiers are used to control whether or not an option appears in the
997 <tt>--help</tt> and <tt>--help-hidden</tt> output for the compiled program:<p>
1001 <a name="cl::NotHidden">The <b><tt>cl::NotHidden</tt></b> modifier (which is the
1002 default for <tt><a href="#cl::opt">cl::opt</a></tt> and <tt><a
1003 href="#cl::list">cl::list</a></tt> options), indicates the option is to appear
1004 in both help listings.<p>
1006 <a name="cl::Hidden">The <b><tt>cl::Hidden</tt></b> modifier (which is the
1007 default for <tt><a href="#cl::alias">cl::alias</a></tt> options), indicates that
1008 the option should not appear in the <tt>--help</tt> output, but should appear in
1009 the <tt>--help-hidden</tt> output.<p>
1011 <a name="cl::ReallyHidden">The <b><tt>cl::ReallyHidden</tt></b> modifier,
1012 indicates that the option should not appear in any help output.<p>
1015 <!-- _______________________________________________________________________ -->
1016 </ul><a name="numoccurances"><h4><hr size=0>Controlling the number of occurances required and allowed</h4><ul>
1018 This group of options is used to control how many time an option is allowed (or
1019 required) to be specified on the command line of your program. Specifying a
1020 value for this setting allows the CommandLine library to do error checking for
1023 The allowed values for this option group are:<p>
1026 <a name="cl::Optional">The <b><tt>cl::Optional</tt></b> modifier (which is the
1027 default for the <tt><a href="#cl::opt">cl::opt</a></tt> and <tt><a
1028 href="#cl::alias">cl::alias</a></tt> classes) indicates that your program will
1029 allow either zero or one occurance of the option to be specified.<p>
1031 <a name="cl::ZeroOrMore">The <b><tt>cl::ZeroOrMore</tt></b> modifier (which is
1032 the default for the <tt><a href="#cl::list">cl::list</a></tt> class) indicates
1033 that your program will allow the option to be specified zero or more times.<p>
1035 <a name="cl::Required">The <b><tt>cl::Required</tt></b> modifier indicates that
1036 the specified option must be specified exactly one time.<p>
1038 <a name="cl::OneOrMore">The <b><tt>cl::OneOrMore</tt></b> modifier indicates
1039 that the option must be specified at least one time.<p>
1041 The <b><tt>cl::ConsumeAfter</tt></b> modifier is described in the <a
1042 href="#positional">Positional arguments section</a><p>
1046 If an option is not specified, then the value of the option is equal to the
1047 value specified by the <tt><a href="#cl::init">cl::init</a></tt> attribute. If
1048 the <tt><a href="#cl::init">cl::init</a></tt> attribute is not specified, the
1049 option value is initialized with the default constructor for the data type.<p>
1051 If an option is specified multiple times for an option of the <tt><a
1052 href="#cl::opt">cl::opt</a></tt> class, only the last value will be retained.<p>
1055 <!-- _______________________________________________________________________ -->
1056 </ul><a name="valrequired"><h4><hr size=0>Controlling whether or not a value must be specified</h4><ul>
1058 This group of options is used to control whether or not the option allows a
1059 value to be present. In the case of the CommandLine library, a value is either
1060 specified with an equal sign (e.g. '<tt>-index-depth=17</tt>') or as a trailing
1061 string (e.g. '<tt>-o a.out</tt>').<p>
1063 The allowed values for this option group are:<p>
1066 <a name="cl::ValueOptional">The <b><tt>cl::ValueOptional</tt></b> modifier
1067 (which is the default for <tt>bool</tt> typed options) specifies that it is
1068 acceptable to have a value, or not. A boolean argument can be enabled just by
1069 appearing on the command line, or it can have an explicit '<tt>-foo=true</tt>'.
1070 If an option is specified with this mode, it is illegal for the value to be
1071 provided without the equal sign. Therefore '<tt>-foo true</tt>' is illegal. To
1072 get this behavior, you must use the <a
1073 href="#cl::ValueRequired">cl::ValueRequired</a> modifier.<p>
1075 <a name="cl::ValueRequired">The <b><tt>cl::ValueRequired</tt></b> modifier
1076 (which is the default for all other types except for <a
1077 href="#onealternative">unnamed alternatives using the generic parser</a>)
1078 specifies that a value must be provided. This mode informs the command line
1079 library that if an option is not provides with an equal sign, that the next
1080 argument provided must be the value. This allows things like '<tt>-o
1081 a.out</tt>' to work.<p>
1083 <a name="cl::ValueDisallowed">The <b><tt>cl::ValueDisallowed</tt></b> modifier
1084 (which is the default for <a href="#onealternative">unnamed alternatives using
1085 the generic parser</a>) indicates that it is a runtime error for the user to specify a value. This can be provided to disallow users from providing options to boolean options (like '<tt>-foo=true</tt>').<p>
1089 In general, the default values for this option group work just like you would
1090 want them to. As mentioned above, you can specify the <a
1091 href="#cl::ValueDisallowed">cl::ValueDisallowed</a> modifier to a boolean
1092 argument to restrict your command line parser. These options are mostly useful
1093 when <a href="#extensionguide">extending the library</a>.<p>
1097 <!-- _______________________________________________________________________ -->
1098 </ul><a name="formatting"><h4><hr size=0>Controlling other formatting options</h4><ul>
1100 The formatting option group is used to specify that the command line option has
1101 special abilities and is otherwise different from other command line arguments.
1102 As usual, you can only specify at most one of these arguments.<p>
1105 <a name="cl::NormalFormatting">The <b><tt>cl::NormalFormatting</tt></b> modifier
1106 (which is the default all options) specifies that this option is "normal".<p>
1108 <a name="cl::Positional">The <b><tt>cl::Positional</tt></b> modifier specifies
1109 that this is a positional argument, that does not have a command line option
1110 associated with it. See the <a href="#positional">Positional Arguments</a>
1111 section for more information.<p>
1113 The <b><a href="#cl::ConsumeAfter"><tt>cl::ConsumeAfter</tt></a></b> modifier
1114 specifies that this option is used to capture "interpreter style" arguments. See <a href="#cl::ConsumeAfter">this section for more information</a>.<p>
1117 <a name="cl::Prefix">The <b><tt>cl::Prefix</tt></b> modifier specifies that this
1118 option prefixes its value. With 'Prefix' options, there is no equal sign that
1119 separates the value from the option name specified. This is useful for
1120 processing odd arguments like '<tt>-lmalloc -L/usr/lib'</tt> in a linker tool.
1121 Here, the '<tt>l</tt>' and '<tt>L</tt>' options are normal string (list)
1122 options, that have the <a href="#cl::Prefix">cl::Prefix</a> modifier added to
1123 allow the CommandLine library to recognize them. Note that <a
1124 href="#cl::Prefix">cl::Prefix</a> options must not have the <a
1125 href="#cl::ValueDisallowed">cl::ValueDisallowed</a> modifier specified.<p>
1127 <a name="cl::Grouping">The <b><tt>cl::Grouping</tt></b> modifier is used to
1128 implement unix style tools (like <tt>ls</tt>) that have lots of single letter
1129 arguments, but only require a single dash. For example, the '<tt>ls -labF</tt>'
1130 command actually enables four different options, all of which are single
1131 letters. Note that <a href="#cl::Grouping">cl::Grouping</a> options cannot have
1136 The CommandLine library does not restrict how you use the <a
1137 href="#cl::Prefix">cl::Prefix</a> or <a href="#cl::Grouping">cl::Grouping</a>
1138 modifiers, but it is possible to specify ambiguous argument settings. Thus, it
1139 is possible to have multiple letter options that are prefix or grouping options,
1140 and they will still work as designed.<p>
1142 To do this, the CommandLine library uses a greedy algorithm to parse the input
1143 option into (potentially multiple) prefix and grouping options. The strategy
1144 basically looks like this:<p>
1146 <tt>parse(string OrigInput) {</tt>
1148 <li><tt>string input = OrigInput;</tt>
1149 <li><tt>if (isOption(input)) return getOption(input).parse();</tt> <i>// Normal option</i>
1150 <li><tt>while (!isOption(input) && !input.empty()) input.pop_back();</tt> <i>// Remove the last letter</i>
1151 <li><tt>if (input.empty()) return error();</tt> <i>// No matching option</i>
1152 <li><tt>if (getOption(input).isPrefix())<br>
1153 return getOption(input).parse(input);</tt>
1154 <li><tt>while (!input.empty()) { <i>// Must be grouping options</i><br>
1155 getOption(input).parse();<br>
1156 OrigInput.erase(OrigInput.begin(), OrigInput.begin()+input.length());<br>
1157 input = OrigInput;<br>
1158 while (!isOption(input) && !input.empty()) input.pop_back();<br>
1160 <li><tt>if (!OrigInput.empty()) error();</tt>
1168 <!-- _______________________________________________________________________ -->
1169 </ul><a name="misc"><h4><hr size=0>Miscellaneous option modifiers</h4><ul>
1171 The miscellaneous option modifiers are the only flags where you can specify more
1172 than one flag from the set: they are not mutually exclusive. These flags
1173 specify boolean properties that modify the option.<p>
1177 <a name="cl::CommaSeparated">The <b><tt>cl::CommaSeparated</tt></b> modifier
1178 indicates that any commas specified for an option's value should be used to
1179 split the value up into multiple values for the option. For example, these two
1180 options are equivalent when <tt>cl::CommaSeparated</tt> is specified:
1181 "<tt>-foo=a -foo=b -foo=c</tt>" and "<tt>-foo=a,b,c</tt>". This option only
1182 makes sense to be used in a case where the option is allowed to accept one or
1183 more values (i.e. it is a <a href="#cl::list">cl::list</a> option).<p>
1186 So far, the only miscellaneous option modifier is the
1187 <tt>cl::CommaSeparated</tt> modifier.<p>
1190 <!-- ======================================================================= -->
1191 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0><tr><td> </td><td width="100%"> <font color="#EEEEFF" face="Georgia,Palatino"><b>
1192 <a name="toplevel">Top-Level Classes and Functions
1193 </b></font></td></tr></table><ul>
1195 Despite all of the builtin flexibility, the CommandLine option library really
1196 only consists of one function (<a
1197 href="#cl::ParseCommandLineOptions"><tt>cl::ParseCommandLineOptions</tt></a>)
1198 and three main classes: <a href="#cl::opt"><tt>cl::opt</tt></a>, <a
1199 href="#cl::list"><tt>cl::list</tt></a>, and <a
1200 href="#cl::alias"><tt>cl::alias</tt></a>. This section describes these three
1201 classes in detail.<p>
1203 <!-- _______________________________________________________________________ -->
1204 </ul><a name="cl::ParseCommandLineOptions"><h4><hr size=0>The
1205 <tt>cl::ParseCommandLineOptions</tt> function</h4><ul>
1207 The <tt>cl::ParseCommandLineOptions</tt> function is designed to be called
1208 directly from <tt>main</tt>, and is used to fill in the values of all of the
1209 command line option variables once <tt>argc</tt> and <tt>argv</tt> are
1212 The <tt>cl::ParseCommandLineOptions</tt> function requires two parameters
1213 (<tt>argc</tt> and <tt>argv</tt>), but may also take an optional third parameter
1214 which holds <a href="#description">additional extra text</a> to emit when the
1215 <tt>--help</tt> option is invoked.<p>
1218 <!-- _______________________________________________________________________ -->
1219 </ul><a name="cl::ParseEnvironmentOptions"><h4><hr size=0>The
1220 <tt>cl::ParseEnvironmentOptions</tt> function</h4><ul>
1222 The <tt>cl::ParseEnvironmentOptions</tt>
1223 function has mostly the same effects as
1224 <a href="#cl::ParseCommandLineOptions"><tt>cl::ParseCommandLineOptions</tt></a>,
1225 except that it is designed to take values for options from an
1226 environment variable, for those cases in which reading the
1227 command line is not convenient or not desired. It fills in
1228 the values of all the command line option variables just like
1229 <a href="#cl::ParseCommandLineOptions"><tt>cl::ParseCommandLineOptions</tt></a>
1232 It takes three parameters: first, the name of the program (since <tt>argv</tt>
1233 may not be available, it can't just look in <tt>argv[0]</tt>), second,
1234 the name of the environment variable to examine, and third, the optional
1235 <a href="#description">additional extra text</a> to emit when the
1236 <tt>--help</tt> option is invoked.<p>
1238 <tt>cl::ParseEnvironmentOptions</tt> will break the environment
1239 variable's value up into words and then process them using
1240 <a href="#cl::ParseCommandLineOptions"><tt>cl::ParseCommandLineOptions</tt></a>.
1241 <b>Note:</b> Currently <tt>cl::ParseEnvironmentOptions</tt> does not support
1242 quoting, so an environment variable containing <tt>-option "foo bar"</tt> will
1243 be parsed as three words, <tt>-option</tt>, <tt>"foo</tt>, and <tt>bar"</tt>,
1244 which is different from what you would get from the shell with the same
1247 <!-- _______________________________________________________________________ -->
1248 </ul><a name="cl::opt"><h4><hr size=0>The <tt>cl::opt</tt> class</h4><ul>
1250 The <tt>cl::opt</tt> class is the class used to represent scalar command line
1251 options, and is the one used most of the time. It is a templated class which
1252 can take up to three arguments (all except for the first have default values
1256 <b>namespace</b> cl {
1257 <b>template</b> <<b>class</b> DataType, <b>bool</b> ExternalStorage = <b>false</b>,
1258 <b>class</b> ParserClass = parser<DataType> >
1263 The first template argument specifies what underlying data type the command line
1264 argument is, and is used to select a default parser implementation. The second
1265 template argument is used to specify whether the option should contain the
1266 storage for the option (the default) or whether external storage should be used
1267 to contain the value parsed for the option (see <a href="#storage">Internal vs
1268 External Storage</a> for more information).<p>
1270 The third template argument specifies which parser to use. The default value
1271 selects an instantiation of the <tt>parser</tt> class based on the underlying
1272 data type of the option. In general, this default works well for most
1273 applications, so this option is only used when using a <a
1274 href="#customparser">custom parser</a>.<p>
1277 <!-- _______________________________________________________________________ -->
1278 </ul><a name="cl::list"><h4><hr size=0>The <tt>cl::list</tt> class</h4><ul>
1280 The <tt>cl::list</tt> class is the class used to represent a list of command
1281 line options. It too is a templated class which can take up to three
1285 <b>namespace</b> cl {
1286 <b>template</b> <<b>class</b> DataType, <b>class</b> Storage = <b>bool</b>,
1287 <b>class</b> ParserClass = parser<DataType> >
1292 This class works the exact same as the <a href="#cl::opt"><tt>cl::opt</tt></a>
1293 class, except that the second argument is the <b>type</b> of the external
1294 storage, not a boolean value. For this class, the marker type '<tt>bool</tt>'
1295 is used to indicate that internal storage should be used.<p>
1298 <!-- _______________________________________________________________________ -->
1299 </ul><a name="cl::alias"><h4><hr size=0>The <tt>cl::alias</tt> class</h4><ul>
1301 The <tt>cl::alias</tt> class is a nontemplated class that is used to form
1302 aliases for other arguments.<p>
1305 <b>namespace</b> cl {
1310 The <a href="#cl::aliasopt"><tt>cl::aliasopt</tt></a> attribute should be used
1311 to specify which option this is an alias for. Alias arguments default to being
1312 <a href="#cl::Hidden">Hidden</a>, and use the aliased options parser to do the
1313 conversion from string to data.<p>
1316 <!-- ======================================================================= -->
1317 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0><tr><td> </td><td width="100%"> <font color="#EEEEFF" face="Georgia,Palatino"><b>
1318 <a name="builtinparsers">Builtin parsers
1319 </b></font></td></tr></table><ul>
1321 Parsers control how the string value taken from the command line is translated
1322 into a typed value, suitable for use in a C++ program. By default, the
1323 CommandLine library uses an instance of <tt>parser<type></tt> if the
1324 command line option specifies that it uses values of type '<tt>type</tt>'.
1325 Because of this, custom option processing is specified with specializations of
1326 the '<tt>parser</tt>' class.<p>
1328 The CommandLine library provides the following builtin parser specializations,
1329 which are sufficient for most applications. It can, however, also be extended to
1330 work with new data types and new ways of interpreting the same data. See the <a
1331 href="#customparser">Writing a Custom Parser</a> for more details on this type
1332 of library extension.<p>
1334 <li><a name="genericparser">The <b>generic <tt>parser<t></tt> parser</b>
1335 can be used to map strings values to any data type, through the use of the <a
1336 href="#cl::values">cl::values</a> property, which specifies the mapping
1337 information. The most common use of this parser is for parsing enum values,
1338 which allows you to use the CommandLine library for all of the error checking to
1339 make sure that only valid enum values are specified (as opposed to accepting
1340 arbitrary strings). Despite this, however, the generic parser class can be used
1341 for any data type.<p>
1343 <li><a name="boolparser">The <b><tt>parser<bool></tt> specialization</b>
1344 is used to convert boolean strings to a boolean value. Currently accepted
1345 strings are "<tt>true</tt>", "<tt>TRUE</tt>", "<tt>True</tt>", "<tt>1</tt>",
1346 "<tt>false</tt>", "<tt>FALSE</tt>", "<tt>False</tt>", and "<tt>0</tt>".<p>
1348 <li><a name="stringparser">The <b><tt>parser<string></tt> specialization</b> simply stores the parsed string into the string value specified. No conversion or modification of the data is performed.<p>
1350 <li><a name="intparser">The <b><tt>parser<int></tt> specialization</b>
1351 uses the C <tt>strtol</tt> function to parse the string input. As such, it will
1352 accept a decimal number (with an optional '+' or '-' prefix) which must start
1353 with a non-zero digit. It accepts octal numbers, which are identified with a
1354 '<tt>0</tt>' prefix digit, and hexadecimal numbers with a prefix of
1355 '<tt>0x</tt>' or '<tt>0X</tt>'.<p>
1357 <li><a name="doubleparser">The <b><tt>parser<double></tt></b> and
1358 <b><tt>parser<float></tt> specializations</b> use the standard C
1359 <tt>strtod</tt> function to convert floating point strings into floating point
1360 values. As such, a broad range of string formats is supported, including
1361 exponential notation (ex: <tt>1.7e15</tt>) and properly supports locales.
1366 <!-- *********************************************************************** -->
1367 </ul><table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0><tr><td align=center><font color="#EEEEFF" size=+2 face="Georgia,Palatino"><b>
1368 <a name="extensionguide">Extension Guide
1369 </b></font></td></tr></table><ul>
1370 <!-- *********************************************************************** -->
1372 Although the CommandLine library has a lot of functionality built into it
1373 already (as discussed previously), one of its true strengths lie in its
1374 extensibility. This section discusses how the CommandLine library works under
1375 the covers and illustrates how to do some simple, common, extensions.<p>
1378 <!-- ======================================================================= -->
1379 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0>
1380 <tr><td> </td><td width="100%"> <font color="#EEEEFF"
1381 face="Georgia,Palatino"><b> <a name="customparser">Writing a custom parser
1382 </b></font></td></tr></table><ul>
1384 One of the simplest and most common extensions is the use of a custom parser.
1385 As <a href="#builtinparsers">discussed previously</a>, parsers are the portion
1386 of the CommandLine library that turns string input from the user into a
1387 particular parsed data type, validating the input in the process.<p>
1389 There are two ways to use a new parser:<p>
1392 <li>Specialize the <a href="#genericparser"><tt>cl::parser</tt></a> template for
1393 your custom data type.<p>
1395 This approach has the advantage that users of your custom data type will
1396 automatically use your custom parser whenever they define an option with a
1397 value type of your data type. The disadvantage of this approach is that it
1398 doesn't work if your fundemental data type is something that is already
1401 <li>Write an independent class, using it explicitly from options that need
1404 This approach works well in situations where you would line to parse an
1405 option using special syntax for a not-very-special data-type. The drawback
1406 of this approach is that users of your parser have to be aware that they are
1407 using your parser, instead of the builtin ones.<p>
1411 To guide the discussion, we will discuss a custom parser that accepts file
1412 sizes, specified with an optional unit after the numeric size. For example, we
1413 would like to parse "102kb", "41M", "1G" into the appropriate integer value. In
1414 this case, the underlying data type we want to parse into is
1415 '<tt>unsigned</tt>'. We choose approach #2 above because we don't want to make
1416 this the default for all <tt>unsigned</tt> options.<p>
1418 To start out, we declare our new <tt>FileSizeParser</tt> class:<p>
1421 <b>struct</b> FileSizeParser : <b>public</b> cl::basic_parser<<b>unsigned</b>> {
1422 <i>// parse - Return true on error.</i>
1423 <b>bool</b> parse(cl::Option &O, <b>const char</b> *ArgName, <b>const</b> std::string &ArgValue,
1424 <b>unsigned</b> &Val);
1428 Our new class inherits from the <tt>cl::basic_parser</tt> template class to fill
1429 in the default, boiler plate, code for us. We give it the data type that we
1430 parse into (the last argument to the <tt>parse</tt> method so that clients of
1431 our custom parser know what object type to pass in to the parse method (here we
1432 declare that we parse into '<tt>unsigned</tt>' variables.<p>
1434 For most purposes, the only method that must be implemented in a custom parser
1435 is the <tt>parse</tt> method. The <tt>parse</tt> method is called whenever the
1436 option is invoked, passing in the option itself, the option name, the string to
1437 parse, and a reference to a return value. If the string to parse is not well formed, the parser should output an error message and return true. Otherwise it should return false and set '<tt>Val</tt>' to the parsed value. In our example, we implement <tt>parse</tt> as:<p>
1440 <b>bool</b> FileSizeParser::parse(cl::Option &O, <b>const char</b> *ArgName,
1441 <b>const</b> std::string &Arg, <b>unsigned</b> &Val) {
1442 <b>const char</b> *ArgStart = Arg.c_str();
1445 <i>// Parse integer part, leaving 'End' pointing to the first non-integer char</i>
1446 Val = (unsigned)strtol(ArgStart, &End, 0);
1449 <b>switch</b> (*End++) {
1450 <b>case</b> 0: <b>return</b> false; <i>// No error</i>
1451 <b>case</b> 'i': <i>// Ignore the 'i' in KiB if people use that</i>
1452 <b>case</b> 'b': <b>case</b> 'B': <i>// Ignore B suffix</i>
1455 <b>case</b> 'g': <b>case</b> 'G': Val *= 1024*1024*1024; <b>break</b>;
1456 <b>case</b> 'm': <b>case</b> 'M': Val *= 1024*1024; <b>break</b>;
1457 <b>case</b> 'k': <b>case</b> 'K': Val *= 1024; <b>break</b>;
1460 <i>// Print an error message if unrecognized character!</i>
1461 <b>return</b> O.error(": '" + Arg + "' value invalid for file size argument!");
1467 This function implements a very simple parser for the kinds of strings we are
1468 interested in. Although it has some holes (it allows "<tt>123KKK</tt>" for
1469 example), it is good enough for this example. Note that we use the option
1470 itself to print out the error message (the <tt>error</tt> method always returns
1471 true) in order to get a nice error message (shown below). Now that we have our
1472 parser class, we can use it like this:<p>
1475 <b>static</b> <a href="#cl::opt">cl::opt</a><<b>unsigned</b>, <b>false</b>, FileSizeParser>
1476 MFS(<i>"max-file-size"</i>, <a href="#cl::desc">cl::desc</a>(<i>"Maximum file size to accept"</i>),
1477 <a href="#cl::value_desc">cl::value_desc</a>("<i>size</i>"));
1480 Which adds this to the output of our program:<p>
1484 -help - display available options (--help-hidden for more)
1486 <b>-max-file-size=<size> - Maximum file size to accept</b>
1489 And we can test that our parse works correctly now (the test program just prints
1490 out the max-file-size argument value):<p>
1495 $ ./test -max-file-size=123MB
1497 $ ./test -max-file-size=3G
1499 $ ./test -max-file-size=dog
1500 -max-file-size option: 'dog' value invalid for file size argument!
1503 It looks like it works. The error message that we get is nice and helpful, and
1504 we seem to accept reasonable file sizes. This wraps up the "custom parser"
1508 <!-- ======================================================================= -->
1509 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0>
1510 <tr><td> </td><td width="100%"> <font color="#EEEEFF"
1511 face="Georgia,Palatino"><b> <a name="explotingexternal">Exploiting external
1512 storage </b></font></td></tr></table><ul>
1516 <!-- ======================================================================= -->
1517 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0>
1518 <tr><td> </td><td width="100%"> <font color="#EEEEFF"
1519 face="Georgia,Palatino"><b> <a name="dynamicopts">Dynamically adding command
1520 line options </b></font></td></tr></table><ul>
1526 <!-- *********************************************************************** -->
1528 <!-- *********************************************************************** -->
1532 <address><a href="mailto:sabre@nondot.org">Chris Lattner</a></address>
1533 <!-- Created: Tue Jan 23 15:19:28 CST 2001 -->
1534 <!-- hhmts start -->
1535 Last modified: Fri Aug 1 16:30:11 CDT 2003