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::opt">The <tt>cl::opt</tt> class</a>
46 <li><a href="#cl::list">The <tt>cl::list</tt> class</a>
47 <li><a href="#cl::alias">The <tt>cl::alias</tt> class</a>
49 <li><a href="#builtinparsers">Builtin parsers</a>
51 <li><a href="#genericparser">The Generic <tt>parser<t></tt>
53 <li><a href="#boolparser">The <tt>parser<bool></tt>
55 <li><a href="#stringparser">The <tt>parser<string></tt>
57 <li><a href="#intparser">The <tt>parser<int></tt>
59 <li><a href="#doubleparser">The <tt>parser<double></tt> and
60 <tt>parser<float></tt> specializations</a>
63 <li><a href="#extensionguide">Extension Guide</a>
65 <li><a href="#customparser">Writing a custom parser</a>
66 <li><a href="#explotingexternal">Exploiting external storage</a>
67 <li><a href="#dynamicopts">Dynamically adding command line options</a>
70 <p><b>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a></b><p>
74 <!-- *********************************************************************** -->
75 <table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0>
76 <tr><td align=center><font color="#EEEEFF" size=+2 face="Georgia,Palatino"><b>
77 <a name="introduction">Introduction
78 </b></font></td></tr></table><ul>
79 <!-- *********************************************************************** -->
81 This document describes the CommandLine argument processing library. It will
82 show you how to use it, and what it can do. The CommandLine library uses a
83 declarative approach to specifying the command line options that your program
84 takes. By default, these options declarations implicitly hold the value parsed
85 for the option declared (of course this <a href="#storage">can be
88 Although there are a <b>lot</b> of command line argument parsing libraries out
89 there in many different languages, none of them fit well with what I needed. By
90 looking at the features and problems of other libraries, I designed the
91 CommandLine library to have the following features:<p>
94 <li>Speed: The CommandLine library is very quick and uses little resources. The
95 parsing time of the library is directly proportional to the number of arguments
96 parsed, not the the number of options recognized. Additionally, command line
97 argument values are captured transparently into user defined global variables,
98 which can be accessed like any other variable (and with the same
101 <li>Type Safe: As a user of CommandLine, you don't have to worry about
102 remembering the type of arguments that you want (is it an int? a string? a
103 bool? an enum?) and keep casting it around. Not only does this help prevent
104 error prone constructs, it also leads to dramatically cleaner source code.<p>
106 <li>No subclasses required: To use CommandLine, you instantiate variables that
107 correspond to the arguments that you would like to capture, you don't subclass a
108 parser. This means that you don't have to write <b>any</b> boilerplate code.<p>
110 <li>Globally accessible: Libraries can specify command line arguments that are
111 automatically enabled in any tool that links to the library. This is possible
112 because the application doesn't have to keep a "list" of arguments to pass to
113 the parser. This also makes supporting <a href="#dynamicopts">dynamically
114 loaded options</a> trivial.<p>
116 <li>Cleaner: CommandLine supports enum and other types directly, meaning that
117 there is less error and more security built into the library. You don't have to
118 worry about whether your integral command line argument accidentally got
119 assigned a value that is not valid for your enum type.<p>
121 <li>Powerful: The CommandLine library supports many different types of
122 arguments, from simple <a href="#boolparser">boolean flags</a> to <a
123 href="#cl::opt">scalars arguments</a> (<a href="#stringparser">strings</a>, <a
124 href="#intparser">integers</a>, <a href="#genericparser">enums</a>, <a
125 href="#doubleparser">doubles</a>), to <a href="#cl::list">lists of
126 arguments</a>. This is possible because CommandLine is...<p>
128 <li>Extensible: It is very simple to add a new argument type to CommandLine.
129 Simply specify the parser that you want to use with the command line option when
130 you declare it. <a href="#customparser">Custom parsers</a> are no problem.<p>
132 <li>Labor Saving: The CommandLine library cuts down on the amount of grunt work
133 that you, the user, have to do. For example, it automatically provides a
134 <tt>--help</tt> option that shows the available command line options for your
135 tool. Additionally, it does most of the basic correctness checking for you.<p>
137 <li>Capable: The CommandLine library can handle lots of different forms of
138 options often found in real programs. For example, <a
139 href="#positional">positional</a> arguments, <tt>ls</tt> style <a
140 href="#cl::Grouping">grouping</a> options (to allow processing '<tt>ls
141 -lad</tt>' naturally), <tt>ld</tt> style <a href="#cl::Prefix">prefix</a>
142 options (to parse '<tt>-lmalloc -L/usr/lib</tt>'), and <a
143 href="#cl::ConsumeAfter">interpreter style options</a>.<p>
147 This document will hopefully let you jump in and start using CommandLine in your
148 utility quickly and painlessly. Additionally it should be a simple reference
149 manual to figure out how stuff works. If it is failing in some area (or you
150 want an extension to the library), nag the author, <a
151 href="mailto:sabre@nondot.org">Chris Lattner</a>.<p>
155 <!-- *********************************************************************** -->
156 </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>
157 <a name="quickstart">Quick Start Guide
158 </b></font></td></tr></table><ul>
159 <!-- *********************************************************************** -->
161 This section of the manual runs through a simple CommandLine'ification of a
162 basic compiler tool. This is intended to show you how to jump into using the
163 CommandLine library in your own program, and show you some of the cool things it
166 To start out, you need to include the CommandLine header file into your
170 #include "Support/CommandLine.h"
173 Additionally, you need to add this as the first line of your main program:<p>
176 int main(int argc, char **argv) {
177 <a href="#cl::ParseCommandLineOptions">cl::ParseCommandLineOptions</a>(argc, argv);
182 ... which actually parses the arguments and fills in the variable
185 Now that you are ready to support command line arguments, we need to tell the
186 system which ones we want, and what type of argument they are. The CommandLine
187 library uses a declarative syntax to model command line arguments with the
188 global variable declarations that capture the parsed values. This means that
189 for every command line option that you would like to support, there should be a
190 global variable declaration to capture the result. For example, in a compiler,
191 we would like to support the unix standard '<tt>-o <filename></tt>' option
192 to specify where to put the output. With the CommandLine library, this is
193 represented like this:<p>
195 <pre><a name="value_desc_example">
196 <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>"));
199 This declares a global variable "<tt>OutputFilename</tt>" that is used to
200 capture the result of the "<tt>o</tt>" argument (first parameter). We specify
201 that this is a simple scalar option by using the "<tt><a
202 href="#cl::opt">cl::opt</a></tt>" template (as opposed to the <a
203 href="#list">"<tt>cl::list</tt> template</a>), and tell the CommandLine library
204 that the data type that we are parsing is a string.<p>
206 The second and third parameters (which are optional) are used to specify what to
207 output for the "<tt>--help</tt>" option. In this case, we get a line that looks
211 USAGE: compiler [options]
214 -help - display available options (--help-hidden for more)
215 <b>-o <filename> - Specify output filename</b>
218 Because we specified that the command line option should parse using the
219 <tt>string</tt> data type, the variable declared is automatically usable as a
220 real string in all contexts that a normal C++ string object may be used. For
225 ofstream Output(OutputFilename.c_str());
230 There are many different options that you can use to customize the command line
231 option handling library, but the above example shows the general interface to
232 these options. The options can be specified in any order, and are specified
233 with helper functions like <a href="#cl::desc"><tt>cl::desc(...)</tt></a>, so
234 there are no positional dependencies to remember. The available options are
235 discussed in detail in the <a href="#referenceguide">Reference Guide</a>.<p>
238 Continuing the example, we would like to have our compiler take an input
239 filename as well as an output filename, but we do not want the input filename to
240 be specified with a hyphen (ie, not <tt>-filename.c</tt>). To support this
241 style of argument, the CommandLine library allows for <a
242 href="#positional">positional</a> arguments to be specified for the program.
243 These positional arguments are filled with command line parameters that are not
244 in option form. We use this feature like this:<p>
247 <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>"));
250 This declaration indicates that the first positional argument should be treated
251 as the input filename. Here we use the <tt><a
252 href="#cl::init">cl::init</a></tt> option to specify an initial value for the
253 command line option, which is used if the option is not specified (if you do not
254 specify a <tt><a href="#cl::init">cl::init</a></tt> modifier for an option, then
255 the default constructor for the data type is used to initialize the value).
256 Command line options default to being optional, so if we would like to require
257 that the user always specify an input filename, we would add the <tt><a
258 href="#cl::Required">cl::Required</a></tt> flag, and we could eliminate the
259 <tt><a href="#cl::init">cl::init</a></tt> modifier, like this:<p>
262 <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>);
265 Again, the CommandLine library does not require the options to be specified in
266 any particular order, so the above declaration is equivalent to:<p>
269 <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>"));
272 By simply adding the <tt><a href="#cl::Required">cl::Required</a></tt> flag, the
273 CommandLine library will automatically issue an error if the argument is not
274 specified, which shifts all of the command line option verification code out of
275 your application into the library. This is just one example of how using flags
276 can alter the default behaviour of the library, on a per-option basis. By
277 adding one of the declarations above, the <tt>--help</tt> option synopsis is now
281 USAGE: compiler [options] <b><input file></b>
284 -help - display available options (--help-hidden for more)
285 -o <filename> - Specify output filename
288 ... indicating that an input filename is expected.<p>
292 <!-- ======================================================================= -->
293 </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>
294 <a name="bool">Boolean Arguments
295 </b></font></td></tr></table><ul>
297 In addition to input and output filenames, we would like the compiler example to
298 support three boolean flags: "<tt>-f</tt>" to force overwriting of the output
299 file, "<tt>--quiet</tt>" to enable quiet mode, and "<tt>-q</tt>" for backwards
300 compatibility with some of our users. We can support these by declaring options
301 of boolean type like this:<p>
304 <a href="#cl::opt">cl::opt</a><bool> Force ("<i>f</i>", <a href="#cl::desc">cl::desc</a>("<i>Overwrite output files</i>"));
305 <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>"));
306 <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>);
309 This does what you would expect: it declares three boolean variables
310 ("<tt>Force</tt>", "<tt>Quiet</tt>", and "<tt>Quiet2</tt>") to recognize these
311 options. Note that the "<tt>-q</tt>" option is specified with the "<a
312 href="#cl::Hidden"><tt>cl::Hidden</tt></a>" flag. This modifier prevents it
313 from being shown by the standard "<tt>--help</tt>" output (note that it is still
314 shown in the "<tt>--help-hidden</tt>" output).<p>
316 The CommandLine library uses a <a href="#builtinparsers">different parser</a>
317 for different data types. For example, in the string case, the argument passed
318 to the option is copied literally into the content of the string variable... we
319 obviously cannot do that in the boolean case, however, so we must use a smarter
320 parser. In the case of the boolean parser, it allows no options (in which case
321 it assigns the value of true to the variable), or it allows the values
322 "<tt>true</tt>" or "<tt>false</tt>" to be specified, allowing any of the
326 compiler -f # No value, 'Force' == true
327 compiler -f=true # Value specified, 'Force' == true
328 compiler -f=TRUE # Value specified, 'Force' == true
329 compiler -f=FALSE # Value specified, 'Force' == false
332 ... you get the idea. The <a href="#boolparser">bool parser</a> just turns the
333 string values into boolean values, and rejects things like '<tt>compiler
334 -f=foo</tt>'. Similarly, the <a href="#doubleparser">float</a>, <a
335 href="#doubleparser">double</a>, and <a href="#intparser">int</a> parsers work
336 like you would expect, using the '<tt>strtol</tt>' and '<tt>strtod</tt>' C
337 library calls to parse the string value into the specified data type.<p>
339 With the declarations above, "<tt>compiler --help</tt>" emits this:<p>
342 USAGE: compiler [options] <input file>
345 <b>-f - Overwrite output files</b>
346 -o - Override output filename
347 <b>-quiet - Don't print informational messages</b>
348 -help - display available options (--help-hidden for more)
351 and "<tt>opt --help-hidden</tt>" prints this:<p>
354 USAGE: compiler [options] <input file>
357 -f - Overwrite output files
358 -o - Override output filename
359 <b>-q - Don't print informational messages</b>
360 -quiet - Don't print informational messages
361 -help - display available options (--help-hidden for more)
364 This brief example has shown you how to use the '<tt><a
365 href="#cl::opt">cl::opt</a></tt>' class to parse simple scalar command line
366 arguments. In addition to simple scalar arguments, the CommandLine library also
367 provides primitives to support CommandLine option <a href="#alias">aliases</a>,
368 and <a href="#list">lists</a> of options.<p>
371 <!-- ======================================================================= -->
372 </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>
373 <a name="alias">Argument Aliases
374 </b></font></td></tr></table><ul>
376 So far, the example works well, except for the fact that we need to check the
377 quiet condition like this now:<p>
381 if (!Quiet && !Quiet2) printInformationalMessage(...);
385 ... which is a real pain! Instead of defining two values for the same
386 condition, we can use the "<tt><a href="#cl::alias">cl::alias</a></tt>" class to make the "<tt>-q</tt>"
387 option an <b>alias</b> for the "<tt>-quiet</tt>" option, instead of providing
391 <a href="#cl::opt">cl::opt</a><bool> Force ("<i>f</i>", <a href="#cl::desc">cl::desc</a>("<i>Overwrite output files</i>"));
392 <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>"));
393 <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));
396 The third line (which is the only one we modified from above) defines a
397 "<tt>-q</tt> alias that updates the "<tt>Quiet</tt>" variable (as specified by
398 the <tt><a href="#cl::aliasopt">cl::aliasopt</a></tt> modifier) whenever it is
399 specified. Because aliases do not hold state, the only thing the program has to
400 query is the <tt>Quiet</tt> variable now. Another nice feature of aliases is
401 that they automatically hide themselves from the <tt>-help</tt> output
402 (although, again, they are still visible in the <tt>--help-hidden
405 Now the application code can simply use:<p>
409 if (!Quiet) printInformationalMessage(...);
413 ... which is much nicer! The "<tt><a href="#cl::alias">cl::alias</a></tt>" can be used to specify an
414 alternative name for any variable type, and has many uses.<p>
418 <!-- ======================================================================= -->
419 </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>
420 <a name="onealternative">Selecting an alternative from a set of possibilities
421 </b></font></td></tr></table><ul>
423 So far, we have seen how the CommandLine library handles builtin types like
424 <tt>std::string</tt>, <tt>bool</tt> and <tt>int</tt>, but how does it handle
425 things it doesn't know about, like enums or '<tt>int*</tt>'s?<p>
427 The answer is that it uses a table driven generic parser (unless you specify
428 your own parser, as described in the <a href="#extensionguide">Extension
429 Guide</a>). This parser maps literal strings to whatever type is required, are
430 requires you to tell it what this mapping should be.<p>
432 Lets say that we would like to add four optimizations levels to our optimizer,
433 using the standard flags "<tt>-g</tt>", "<tt>-O0</tt>", "<tt>-O1</tt>", and
434 "<tt>-O2</tt>". We could easily implement this with boolean options like above,
435 but there are several problems with this strategy:<p>
438 <li>A user could specify more than one of the options at a time, for example,
439 "<tt>opt -O3 -O2</tt>". The CommandLine library would not be able to catch this
440 erroneous input for us.
442 <li>We would have to test 4 different variables to see which ones are set.
444 <li>This doesn't map to the numeric levels that we want... so we cannot easily
445 see if some level >= "<tt>-O1</tt>" is enabled.
449 To cope with these problems, we can use an enum value, and have the CommandLine
450 library fill it in with the appropriate level directly, which is used like
458 <a href="#cl::opt">cl::opt</a><OptLevel> OptimizationLevel(<a href="#cl::desc">cl::desc</a>("<i>Choose optimization level:</i>"),
459 <a href="#cl::values">cl::values</a>(
460 clEnumVal(g , "<i>No optimizations, enable debugging</i>"),
461 clEnumVal(O1, "<i>Enable trivial optimizations</i>"),
462 clEnumVal(O2, "<i>Enable default optimizations</i>"),
463 clEnumVal(O3, "<i>Enable expensive optimizations</i>"),
467 if (OptimizationLevel >= O2) doPartialRedundancyElimination(...);
471 This declaration defines a variable "<tt>OptimizationLevel</tt>" of the
472 "<tt>OptLevel</tt>" enum type. This variable can be assigned any of the values
473 that are listed in the declaration (Note that the declaration list must be
474 terminated with the "<tt>0</tt>" argument!). The CommandLine library enforces
475 that the user can only specify one of the options, and it ensure that only valid
476 enum values can be specified. The "<tt>clEnumVal</tt>" macros ensure that the
477 command line arguments matched the enum values. With this option added, our
478 help output now is:<p>
481 USAGE: compiler [options] <input file>
484 <b>Choose optimization level:
485 -g - No optimizations, enable debugging
486 -O1 - Enable trivial optimizations
487 -O2 - Enable default optimizations
488 -O3 - Enable expensive optimizations</b>
489 -f - Overwrite output files
490 -help - display available options (--help-hidden for more)
491 -o <filename> - Specify output filename
492 -quiet - Don't print informational messages
495 In this case, it is sort of awkward that flag names correspond directly to enum
496 names, because we probably don't want a enum definition named "<tt>g</tt>" in
497 our program. Because of this, we can alternatively write this example like
505 <a href="#cl::opt">cl::opt</a><OptLevel> OptimizationLevel(<a href="#cl::desc">cl::desc</a>("<i>Choose optimization level:</i>"),
506 <a href="#cl::values">cl::values</a>(
507 clEnumValN(Debug, "g", "<i>No optimizations, enable debugging</i>"),
508 clEnumVal(O1 , "<i>Enable trivial optimizations</i>"),
509 clEnumVal(O2 , "<i>Enable default optimizations</i>"),
510 clEnumVal(O3 , "<i>Enable expensive optimizations</i>"),
514 if (OptimizationLevel == Debug) outputDebugInfo(...);
518 By using the "<tt>clEnumValN</tt>" macro instead of "<tt>clEnumVal</tt>", we can
519 directly specify the name that the flag should get. In general a direct mapping
520 is nice, but sometimes you can't or don't want to preserve the mapping, which is
521 when you would use it.<p>
525 <!-- ======================================================================= -->
526 </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>
527 <a name="namedalternatives">Named Alternatives
528 </b></font></td></tr></table><ul>
530 Another useful argument form is a named alternative style. We shall use this
531 style in our compiler to specify different debug levels that can be used.
532 Instead of each debug level being its own switch, we want to support the
533 following options, of which only one can be specified at a time:
534 "<tt>--debug-level=none</tt>", "<tt>--debug-level=quick</tt>",
535 "<tt>--debug-level=detailed</tt>". To do this, we use the exact same format as
536 our optimization level flags, but we also specify an option name. For this
537 case, the code looks like this:<p>
541 nodebuginfo, quick, detailed
544 // Enable Debug Options to be specified on the command line
545 <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>"),
546 <a href="#cl::values">cl::values</a>(
547 clEnumValN(nodebuginfo, "none", "<i>disable debug information</i>"),
548 clEnumVal(quick, "<i>enable quick debug information</i>"),
549 clEnumVal(detailed, "<i>enable detailed debug information</i>"),
553 This definition defines an enumerated command line variable of type "<tt>enum
554 DebugLev</tt>", which works exactly the same way as before. The difference here
555 is just the interface exposed to the user of your program and the help output by
556 the "<tt>--help</tt>" option:<p>
559 USAGE: compiler [options] <input file>
562 Choose optimization level:
563 -g - No optimizations, enable debugging
564 -O1 - Enable trivial optimizations
565 -O2 - Enable default optimizations
566 -O3 - Enable expensive optimizations
567 <b>-debug_level - Set the debugging level:
568 =none - disable debug information
569 =quick - enable quick debug information
570 =detailed - enable detailed debug information</b>
571 -f - Overwrite output files
572 -help - display available options (--help-hidden for more)
573 -o <filename> - Specify output filename
574 -quiet - Don't print informational messages
577 Again, the only structural difference between the debug level declaration and
578 the optimiation level declaration is that the debug level declaration includes
579 an option name (<tt>"debug_level"</tt>), which automatically changes how the
580 library processes the argument. The CommandLine library supports both forms so
581 that you can choose the form most appropriate for your application.<p>
585 <!-- ======================================================================= -->
586 </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>
587 <a name="list">Parsing a list of options
588 </b></font></td></tr></table><ul>
590 Now that we have the standard run of the mill argument types out of the way,
591 lets get a little wild and crazy. Lets say that we want our optimizer to accept
592 a <b>list</b> of optimizations to perform, allowing duplicates. For example, we
593 might want to run: "<tt>compiler -dce -constprop -inline -dce -strip</tt>". In
594 this case, the order of the arguments and the number of appearances is very
595 important. This is what the "<tt><a href="#cl::list">cl::list</a></tt>"
596 template is for. First, start by defining an enum of the optimizations that you
597 would like to perform:<p>
601 // 'inline' is a C++ keyword, so name it 'inlining'
602 dce, constprop, inlining, strip
606 Then define your "<tt><a href="#cl::list">cl::list</a></tt>" variable:<p>
609 <a href="#cl::list">cl::list</a><Opts> OptimizationList(<a href="#cl::desc">cl::desc</a>("<i>Available Optimizations:</i>"),
610 <a href="#cl::values">cl::values</a>(
611 clEnumVal(dce , "<i>Dead Code Elimination</i>"),
612 clEnumVal(constprop , "<i>Constant Propagation</i>"),
613 clEnumValN(inlining, "<i>inline</i>", "<i>Procedure Integration</i>"),
614 clEnumVal(strip , "<i>Strip Symbols</i>"),
618 This defines a variable that is conceptually of the type
619 "<tt>std::vector<enum Opts></tt>". Thus, you can access it with standard
623 for (unsigned i = 0; i != OptimizationList.size(); ++i)
624 switch (OptimizationList[i])
628 ... to iterate through the list of options specified.<p>
630 Note that the "<tt><a href="#cl::list">cl::list</a></tt>" template is completely general and may be used
631 with any data types or other arguments that you can use with the
632 "<tt><a href="#cl::opt">cl::opt</a></tt>" template. One especially useful way to use a list is to
633 capture all of the positional arguments together if there may be more than one
634 specified. In the case of a linker, for example, the linker takes several
635 '<tt>.o</tt>' files, and needs to capture them into a list. This is naturally
640 <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>);
644 This variable works just like a "<tt>vector<string></tt>" object. As
645 such, accessing the list is simple, just like above. In this example, we used
646 the <tt><a href="#cl::OneOrMore">cl::OneOrMore</a></tt> modifier to inform the
647 CommandLine library that it is an error if the user does not specify any
648 <tt>.o</tt> files on our command line. Again, this just reduces the amount of
649 checking we have to do.<p>
653 <!-- ======================================================================= -->
654 </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>
655 <a name="description">Adding freeform text to help output
656 </b></font></td></tr></table><ul>
658 As our program grows and becomes more mature, we may decide to put summary
659 information about what it does into the help output. The help output is styled
660 to look similar to a Unix <tt>man</tt> page, providing concise information about
661 a program. Unix <tt>man</tt> pages, however often have a description about what
662 the program does. To add this to your CommandLine program, simply pass a third
664 href="#cl::ParseCommandLineOptions"><tt>cl::ParseCommandLineOptions</tt></a>
665 call in main. This additional argument is then printed as the overview
666 information for your program, allowing you to include any additional information
667 that you want. For example:<p>
670 int main(int argc, char **argv) {
671 <a href="#cl::ParseCommandLineOptions">cl::ParseCommandLineOptions</a>(argc, argv, " CommandLine compiler example\n\n"
672 " This program blah blah blah...\n");
677 Would yield the help output:
680 <b>OVERVIEW: CommandLine compiler example
682 This program blah blah blah...</b>
684 USAGE: compiler [options] <input file>
688 -help - display available options (--help-hidden for more)
689 -o <filename> - Specify output filename
695 <!-- *********************************************************************** -->
696 </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>
697 <a name="referenceguide">Reference Guide
698 </b></font></td></tr></table><ul>
699 <!-- *********************************************************************** -->
701 Now that you know the basics of how to use the CommandLine library, this section
702 will give you the detailed information you need to tune how command line options
703 work, as well as information on more "advanced" command line option processing
707 <!-- ======================================================================= -->
708 </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>
709 <a name="positional">Positional Arguments
710 </b></font></td></tr></table><ul>
712 Positional arguments are those arguments that are not named, and are not
713 specified with a hyphen. Positional arguments should be used when an option is
714 specified by its position alone. For example, the standard Unix <tt>grep</tt>
715 tool takes a regular expression argument, and an optional filename to search
716 through (which defaults to standard input if a filename is not specified).
717 Using the CommandLine library, this would be specified as:<p>
720 <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>);
721 <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>"));
724 Given these two option declarations, the <tt>--help</tt> output for our grep
725 replacement would look like this:<p>
728 USAGE: spiffygrep [options] <b><regular expression> <input file></b>
731 -help - display available options (--help-hidden for more)
734 ... and the resultant program could be used just like the standard <tt>grep</tt>
737 Positional arguments are sorted by their order of construction. This means that
738 command line options will be ordered according to how they are listed in a .cpp
739 file, but will not have an ordering defined if they positional arguments are
740 defined in multiple .cpp files. The fix for this problem is simply to define
741 all of your positional arguments in one .cpp file.<p>
745 <!-- _______________________________________________________________________ -->
746 </ul><a name="--"><h4><hr size=0>Specifying positional options with hyphens</h4><ul>
748 Sometimes you may want to specify a value to your positional argument that
749 starts with a hyphen (for example, searching for '<tt>-foo</tt>' in a file). At
750 first, you will have trouble doing this, because it will try to find an argument
751 named '<tt>-foo</tt>', and will fail (and single quotes will not save you).
752 Note that the system <tt>grep</tt> has the same problem:<p>
755 $ spiffygrep '-foo' test.txt
756 Unknown command line argument '-foo'. Try: spiffygrep --help'
758 $ grep '-foo' test.txt
759 grep: illegal option -- f
760 grep: illegal option -- o
761 grep: illegal option -- o
762 Usage: grep -hblcnsviw pattern file . . .
765 The solution for this problem is the same for both your tool and the system
766 version: use the '<tt>--</tt>' marker. When the user specifies '<tt>--</tt>' on
767 the command line, it is telling the program that all options after the
768 '<tt>--</tt>' should be treated as positional arguments, not options. Thus, we
769 can use it like this:<p>
772 $ spiffygrep -- -foo test.txt
778 <!-- _______________________________________________________________________ -->
779 </ul><a name="cl::ConsumeAfter"><h4><hr size=0>The <tt>cl::ConsumeAfter</tt> modifier</h4><ul>
781 The <tt>cl::ConsumeAfter</tt> <a href="#formatting">formatting option</a> is
782 used to construct programs that use "interpreter style" option processing. With
783 this style of option processing, all arguments specified after the last
784 positional argument are treated as special interpreter arguments that are not
785 interpreted by the command line argument.<p>
787 As a concrete example, lets say we are developing a replacement for the standard
788 Unix Bourne shell (<tt>/bin/sh</tt>). To run <tt>/bin/sh</tt>, first you
789 specify options to the shell itself (like <tt>-x</tt> which turns on trace
790 output), then you specify the name of the script to run, then you specify
791 arguments to the script. These arguments to the script are parsed by the bourne
792 shell command line option processor, but are not interpreted as options to the
793 shell itself. Using the CommandLine library, we would specify this as:<p>
796 <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>("-"));
797 <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>"));
798 <a href="#cl::opt">cl::opt</a><bool> Trace("<i>x</i>", <a href="#cl::desc">cl::desc</a>("<i>Enable trace output</i>"));
801 which automatically provides the help output:<p>
804 USAGE: spiffysh [options] <b><input script> <program arguments>...</b>
807 -help - display available options (--help-hidden for more)
808 <b>-x - Enable trace output</b>
811 At runtime, if we run our new shell replacement as '<tt>spiffysh -x test.sh -a
812 -x -y bar</tt>', the <tt>Trace</tt> variable will be set to true, the
813 <tt>Script</tt> variable will be set to "<tt>test.sh</tt>", and the
814 <tt>Argv</tt> list will contain <tt>["-a", "-x", "-y", "bar"]</tt>, because
815 they were specified after the last positional argument (which is the script
818 There are several limitations to when <tt>cl::ConsumeAfter</tt> options can be
819 specified. For example, only one <tt>cl::ConsumeAfter</tt> can be specified per
820 program, there must be at least one <a href="#positional">positional
821 argument</a> specified, and the <tt>cl::ConsumeAfter</tt> option should be a <a
822 href="#cl::list">cl::list</a> option.<p>
826 <!-- ======================================================================= -->
827 </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>
828 <a name="storage">Internal vs External Storage
829 </b></font></td></tr></table><ul>
831 By default, all command line options automatically hold the value that they
832 parse from the command line. This is very convenient in the common case,
833 especially when combined with the ability to define command line options in the
834 files that use them. This is called the internal storage model.<p>
836 Sometimes, however, it is nice to separate the command line option processing
837 code from the storage of the value parsed. For example, lets say that we have a
838 '<tt>-debug</tt>' option that we would like to use to enable debug information
839 across the entire body of our program. In this case, the boolean value
840 controlling the debug code should be globally accessable (in a header file, for
841 example) yet the command line option processing code should not be exposed to
842 all of these clients (requiring lots of .cpp files to #include
843 <tt>CommandLine.h</tt>).<p>
845 To do this, set up your .h file with your option, like this for example:<p>
848 <i>// DebugFlag.h - Get access to the '-debug' command line option
851 // DebugFlag - This boolean is set to true if the '-debug' command line option
852 // is specified. This should probably not be referenced directly, instead, use
853 // the DEBUG macro below.
855 extern bool DebugFlag;
857 <i>// DEBUG macro - This macro should be used by code to emit debug information.
858 // In the '-debug' option is specified on the command line, and if this is a
859 // debug build, then the code specified as the option to the macro will be
860 // executed. Otherwise it will not be. Example:
862 // DEBUG(cerr << "Bitset contains: " << Bitset << "\n");
864 <font color=red>#ifdef NDEBUG
867 #define DEBUG(X)</font> \
868 do { if (DebugFlag) { X; } } while (0)
869 <font color=red>#endif</font>
872 This allows clients to blissfully use the <tt>DEBUG()</tt> macro, or the
873 <tt>DebugFlag</tt> explicitly if they want to. Now we just need to be able to
874 set the <tt>DebugFlag</tt> boolean when the option is set. To do this, we pass
875 an additial argument to our command line argument processor, and we specify
876 where to fill in with the <a href="#cl::location">cl::location</a> attribute:<p>
879 bool DebugFlag; <i>// the actual value</i>
880 static <a href="#cl::opt">cl::opt</a><bool, true> <i>// The parser</i>
881 Debug("<i>debug</i>", <a href="#cl::desc">cl::desc</a>("<i>Enable debug output</i>")</a>, <a href="#cl::Hidden">cl::Hidden</a>,
882 <a href="#cl::location">cl::location</a>(DebugFlag));
885 In the above example, we specify "<tt>true</tt>" as the second argument to the
886 <a href="#cl::opt">cl::opt</a> template, indicating that the template should not
887 maintain a copy of the value itself. In addition to this, we specify the <a
888 href="#cl::location">cl::location</a> attribute, so that <tt>DebugFlag</tt> is
889 automatically set.<p>
893 <!-- ======================================================================= -->
894 </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>
895 <a name="attributes">Option Attributes
896 </b></font></td></tr></table><ul>
898 This section describes the basic attributes that you can specify on options.<p>
902 <li>The option name attribute (which is required for all options, except <a
903 href="#positional">positional options</a>) specifies what the option name is.
904 This option is specified in simple double quotes:<p>
907 <a href="#cl::opt">cl::opt</a><<b>bool</b>> Quiet("<i>quiet</i>");
910 <li><a name="cl::desc">The <b><tt>cl::desc</tt></b> attribute specifies a
911 description for the option to be shown in the <tt>--help</tt> output for the
914 <li><a name="cl::value_desc">The <b><tt>cl::value_desc</tt></b> attribute
915 specifies a string that can be used to fine tune the <tt>--help</tt> output for
916 a command line option. Look <a href="#value_desc_example">here</a> for an
919 <li><a name="cl::init">The <b><tt>cl::init</tt></b> attribute specifies an
920 inital value for a <a href="#cl::opt">scalar</a> option. If this attribute is
921 not specified then the command line option value defaults to the value created
922 by the default constructor for the type.<p>
924 <li><a name="cl::location">The <b><tt>cl::location</tt></b> attribute where to
925 store the value for a parsed command line option if using external storage. See
926 the section on <a href="#storage">Internal vs External Storage</a> for more
929 <li><a name="cl::aliasopt">The <b><tt>cl::aliasopt</tt></b> attribute specifies
930 which option a <a href="#cl::alias">cl::alias</a> option is an alias for.<p>
932 <li><a name="cl::values">The <b><tt>cl::values</tt></b> attribute specifies the
933 string-to-value mapping to be used by the generic parser. It takes a <b>null
934 terminated</b> list of (option, value, description) triplets that specify the
935 option name, the value mapped to, and the description shown in the
936 <tt>--help</tt> for the tool. Because the generic parser is used most frequently with enum values, two macros are often useful:<p>
938 <li><a name="clEnumVal">The <b><tt>clEnumVal</tt></b> macro is used as a nice
939 simple way to specify a triplet for an enum. This macro automatically makes the
940 option name be the same as the enum name. The first option to the macro is the
941 enum, the second is the description for the command line option.<p> <li><a
942 name="clEnumValN">The <b><tt>clEnumValN</tt></b> macro is used to specify macro
943 options where the option name doesn't equal the enum name. For this macro, the
944 first argument is the enum value, the second is the flag name, and the second is
948 You will get a compile time error if you try to use cl::values with a parser
949 that does not support it.<p>
955 <!-- ======================================================================= -->
956 </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>
957 <a name="modifiers">Option Modifiers
958 </b></font></td></tr></table><ul>
960 Option modifiers are the flags and expressions that you pass into the
961 constructors for <tt><a href="#cl::opt">cl::opt</a></tt> and <tt><a
962 href="#cl::list">cl::list</a></tt>. These modifiers give you the ability to
963 tweak how options are parsed and how <tt>--help</tt> output is generated to fit
964 your application well.<p>
966 These options fall into five main catagories:<p>
969 <li><a href="#hiding">Hiding an option from <tt>--help</tt> output</a>
970 <li><a href="#numoccurances">Controlling the number of occurances
971 required and allowed</a>
972 <li><a href="#valrequired">Controlling whether or not a value must be
974 <li><a href="#formatting">Controlling other formatting options</a>
975 <li><a href="#misc">Miscellaneous option modifiers</a>
978 It is not possible to specify two options from the same catagory (you'll get a
979 runtime error) to a single option, except for options in the miscellaneous
980 catagory. The CommandLine library specifies defaults for all of these settings
981 that are the most useful in practice and the most common, which mean that you
982 usually shouldn't have to worry about these.<p>
985 <!-- _______________________________________________________________________ -->
986 </ul><a name="hiding"><h4><hr size=0>Hiding an option from <tt>--help</tt> output</h4><ul>
988 The <tt>cl::NotHidden</tt>, <tt>cl::Hidden</tt>, and <tt>cl::ReallyHidden</tt>
989 modifiers are used to control whether or not an option appears in the
990 <tt>--help</tt> and <tt>--help-hidden</tt> output for the compiled program:<p>
994 <a name="cl::NotHidden">The <b><tt>cl::NotHidden</tt></b> modifier (which is the
995 default for <tt><a href="#cl::opt">cl::opt</a></tt> and <tt><a
996 href="#cl::list">cl::list</a></tt> options), indicates the option is to appear
997 in both help listings.<p>
999 <a name="cl::Hidden">The <b><tt>cl::Hidden</tt></b> modifier (which is the
1000 default for <tt><a href="#cl::alias">cl::alias</a></tt> options), indicates that
1001 the option should not appear in the <tt>--help</tt> output, but should appear in
1002 the <tt>--help-hidden</tt> output.<p>
1004 <a name="cl::ReallyHidden">The <b><tt>cl::ReallyHidden</tt></b> modifier,
1005 indicates that the option should not appear in any help output.<p>
1008 <!-- _______________________________________________________________________ -->
1009 </ul><a name="numoccurances"><h4><hr size=0>Controlling the number of occurances required and allowed</h4><ul>
1011 This group of options is used to control how many time an option is allowed (or
1012 required) to be specified on the command line of your program. Specifying a
1013 value for this setting allows the CommandLine library to do error checking for
1016 The allowed values for this option group are:<p>
1019 <a name="cl::Optional">The <b><tt>cl::Optional</tt></b> modifier (which is the
1020 default for the <tt><a href="#cl::opt">cl::opt</a></tt> and <tt><a
1021 href="#cl::alias">cl::alias</a></tt> classes) indicates that your program will
1022 allow either zero or one occurance of the option to be specified.<p>
1024 <a name="cl::ZeroOrMore">The <b><tt>cl::ZeroOrMore</tt></b> modifier (which is
1025 the default for the <tt><a href="#cl::list">cl::list</a></tt> class) indicates
1026 that your program will allow the option to be specified zero or more times.<p>
1028 <a name="cl::Required">The <b><tt>cl::Required</tt></b> modifier indicates that
1029 the specified option must be specified exactly one time.<p>
1031 <a name="cl::OneOrMore">The <b><tt>cl::OneOrMore</tt></b> modifier indicates
1032 that the option must be specified at least one time.<p>
1034 The <b><tt>cl::ConsumeAfter</tt></b> modifier is described in the <a
1035 href="#positional">Positional arguments section</a><p>
1039 If an option is not specified, then the value of the option is equal to the
1040 value specified by the <tt><a href="#cl::init">cl::init</a></tt> attribute. If
1041 the <tt><a href="#cl::init">cl::init</a></tt> attribute is not specified, the
1042 option value is initialized with the default constructor for the data type.<p>
1044 If an option is specified multiple times for an option of the <tt><a
1045 href="#cl::opt">cl::opt</a></tt> class, only the last value will be retained.<p>
1048 <!-- _______________________________________________________________________ -->
1049 </ul><a name="valrequired"><h4><hr size=0>Controlling whether or not a value must be specified</h4><ul>
1051 This group of options is used to control whether or not the option allows a
1052 value to be present. In the case of the CommandLine library, a value is either
1053 specified with an equal sign (e.g. '<tt>-index-depth=17</tt>') or as a trailing
1054 string (e.g. '<tt>-o a.out</tt>').<p>
1056 The allowed values for this option group are:<p>
1059 <a name="cl::ValueOptional">The <b><tt>cl::ValueOptional</tt></b> modifier
1060 (which is the default for <tt>bool</tt> typed options) specifies that it is
1061 acceptable to have a value, or not. A boolean argument can be enabled just by
1062 appearing on the command line, or it can have an explicit '<tt>-foo=true</tt>'.
1063 If an option is specified with this mode, it is illegal for the value to be
1064 provided without the equal sign. Therefore '<tt>-foo true</tt>' is illegal. To
1065 get this behavior, you must use the <a
1066 href="#cl::ValueRequired">cl::ValueRequired</a> modifier.<p>
1068 <a name="cl::ValueRequired">The <b><tt>cl::ValueRequired</tt></b> modifier
1069 (which is the default for all other types except for <a
1070 href="#onealternative">unnamed alternatives using the generic parser</a>)
1071 specifies that a value must be provided. This mode informs the command line
1072 library that if an option is not provides with an equal sign, that the next
1073 argument provided must be the value. This allows things like '<tt>-o
1074 a.out</tt>' to work.<p>
1076 <a name="cl::ValueDisallowed">The <b><tt>cl::ValueDisallowed</tt></b> modifier
1077 (which is the default for <a href="#onealternative">unnamed alternatives using
1078 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>
1082 In general, the default values for this option group work just like you would
1083 want them to. As mentioned above, you can specify the <a
1084 href="#cl::ValueDisallowed">cl::ValueDisallowed</a> modifier to a boolean
1085 argument to restrict your command line parser. These options are mostly useful
1086 when <a href="#extensionguide">extending the library</a>.<p>
1090 <!-- _______________________________________________________________________ -->
1091 </ul><a name="formatting"><h4><hr size=0>Controlling other formatting options</h4><ul>
1093 The formatting option group is used to specify that the command line option has
1094 special abilities and is otherwise different from other command line arguments.
1095 As usual, you can only specify at most one of these arguments.<p>
1098 <a name="cl::NormalFormatting">The <b><tt>cl::NormalFormatting</tt></b> modifier
1099 (which is the default all options) specifies that this option is "normal".<p>
1101 <a name="cl::Positional">The <b><tt>cl::Positional</tt></b> modifier specifies
1102 that this is a positional argument, that does not have a command line option
1103 associated with it. See the <a href="#positional">Positional Arguments</a>
1104 section for more information.<p>
1106 The <b><a href="#cl::ConsumeAfter"><tt>cl::ConsumeAfter</tt></a></b> modifier
1107 specifies that this option is used to capture "interpreter style" arguments. See <a href="#cl::ConsumeAfter">this section for more information</a>.<p>
1110 <a name="cl::Prefix">The <b><tt>cl::Prefix</tt></b> modifier specifies that this
1111 option prefixes its value. With 'Prefix' options, there is no equal sign that
1112 separates the value from the option name specified. This is useful for
1113 processing odd arguments like '<tt>-lmalloc -L/usr/lib'</tt> in a linker tool.
1114 Here, the '<tt>l</tt>' and '<tt>L</tt>' options are normal string (list)
1115 options, that have the <a href="#cl::Prefix">cl::Prefix</a> modifier added to
1116 allow the CommandLine library to recognize them. Note that <a
1117 href="#cl::Prefix">cl::Prefix</a> options must not have the <a
1118 href="#cl::ValueDisallowed">cl::ValueDisallowed</a> modifier specified.<p>
1120 <a name="cl::Grouping">The <b><tt>cl::Grouping</tt></b> modifier is used to
1121 implement unix style tools (like <tt>ls</tt>) that have lots of single letter
1122 arguments, but only require a single dash. For example, the '<tt>ls -labF</tt>'
1123 command actually enables four different options, all of which are single
1124 letters. Note that <a href="#cl::Grouping">cl::Grouping</a> options cannot have
1129 The CommandLine library does not restrict how you use the <a
1130 href="#cl::Prefix">cl::Prefix</a> or <a href="#cl::Grouping">cl::Grouping</a>
1131 modifiers, but it is possible to specify ambiguous argument settings. Thus, it
1132 is possible to have multiple letter options that are prefix or grouping options,
1133 and they will still work as designed.<p>
1135 To do this, the CommandLine library uses a greedy algorithm to parse the input
1136 option into (potentially multiple) prefix and grouping options. The strategy
1137 basically looks like this:<p>
1139 <tt>parse(string OrigInput) {</tt>
1141 <li><tt>string input = OrigInput;</tt>
1142 <li><tt>if (isOption(input)) return getOption(input).parse();</tt> <i>// Normal option</i>
1143 <li><tt>while (!isOption(input) && !input.empty()) input.pop_back();</tt> <i>// Remove the last letter</i>
1144 <li><tt>if (input.empty()) return error();</tt> <i>// No matching option</i>
1145 <li><tt>if (getOption(input).isPrefix())<br>
1146 return getOption(input).parse(input);</tt>
1147 <li><tt>while (!input.empty()) { <i>// Must be grouping options</i><br>
1148 getOption(input).parse();<br>
1149 OrigInput.erase(OrigInput.begin(), OrigInput.begin()+input.length());<br>
1150 input = OrigInput;<br>
1151 while (!isOption(input) && !input.empty()) input.pop_back();<br>
1153 <li><tt>if (!OrigInput.empty()) error();</tt>
1161 <!-- _______________________________________________________________________ -->
1162 </ul><a name="misc"><h4><hr size=0>Miscellaneous option modifiers</h4><ul>
1164 The miscellaneous option modifiers are the only flags where you can specify more
1165 than one flag from the set: they are not mutually exclusive. These flags
1166 specify boolean properties that modify the option.<p>
1170 <a name="cl::CommaSeparated">The <b><tt>cl::CommaSeparated</tt></b> modifier
1171 indicates that any commas specified for an option's value should be used to
1172 split the value up into multiple values for the option. For example, these two
1173 options are equivalent when <tt>cl::CommaSeparated</tt> is specified:
1174 "<tt>-foo=a -foo=b -foo=c</tt>" and "<tt>-foo=a,b,c</tt>". This option only
1175 makes sense to be used in a case where the option is allowed to accept one or
1176 more values (i.e. it is a <a href="#cl::list">cl::list</a> option).<p>
1179 So far, the only miscellaneous option modifier is the
1180 <tt>cl::CommaSeparated</tt> modifier.<p>
1183 <!-- ======================================================================= -->
1184 </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>
1185 <a name="toplevel">Top-Level Classes and Functions
1186 </b></font></td></tr></table><ul>
1188 Despite all of the builtin flexibility, the CommandLine option library really
1189 only consists of one function (<a
1190 href="#cl::ParseCommandLineOptions"><tt>cl::ParseCommandLineOptions</tt></a>)
1191 and three main classes: <a href="#cl::opt"><tt>cl::opt</tt></a>, <a
1192 href="#cl::list"><tt>cl::list</tt></a>, and <a
1193 href="#cl::alias"><tt>cl::alias</tt></a>. This section describes these three
1194 classes in detail.<p>
1196 <!-- _______________________________________________________________________ -->
1197 </ul><a name="cl::ParseCommandLineOptions"><h4><hr size=0>The
1198 <tt>cl::ParseCommandLineOptions</tt> function</h4><ul>
1200 The <tt>cl::ParseCommandLineOptions</tt> function is designed to be called
1201 directly from <tt>main</tt>, and is used to fill in the values of all of the
1202 command line option variables once <tt>argc</tt> and <tt>argv</tt> are
1205 The <tt>cl::ParseCommandLineOptions</tt> function requires two parameters
1206 (<tt>argc</tt> and <tt>argv</tt>), but may also take an optional third parameter
1207 which holds <a href="#description">additional extra text</a> to emit when the
1208 <tt>--help</tt> option is invoked.<p>
1211 <!-- _______________________________________________________________________ -->
1212 </ul><a name="cl::opt"><h4><hr size=0>The <tt>cl::opt</tt> class</h4><ul>
1214 The <tt>cl::opt</tt> class is the class used to represent scalar command line
1215 options, and is the one used most of the time. It is a templated class which
1216 can take up to three arguments (all except for the first have default values
1220 <b>namespace</b> cl {
1221 <b>template</b> <<b>class</b> DataType, <b>bool</b> ExternalStorage = <b>false</b>,
1222 <b>class</b> ParserClass = parser<DataType> >
1227 The first template argument specifies what underlying data type the command line
1228 argument is, and is used to select a default parser implementation. The second
1229 template argument is used to specify whether the option should contain the
1230 storage for the option (the default) or whether external storage should be used
1231 to contain the value parsed for the option (see <a href="#storage">Internal vs
1232 External Storage</a> for more information).<p>
1234 The third template argument specifies which parser to use. The default value
1235 selects an instantiation of the <tt>parser</tt> class based on the underlying
1236 data type of the option. In general, this default works well for most
1237 applications, so this option is only used when using a <a
1238 href="#customparser">custom parser</a>.<p>
1241 <!-- _______________________________________________________________________ -->
1242 </ul><a name="cl::list"><h4><hr size=0>The <tt>cl::list</tt> class</h4><ul>
1244 The <tt>cl::list</tt> class is the class used to represent a list of command
1245 line options. It too is a templated class which can take up to three
1249 <b>namespace</b> cl {
1250 <b>template</b> <<b>class</b> DataType, <b>class</b> Storage = <b>bool</b>,
1251 <b>class</b> ParserClass = parser<DataType> >
1256 This class works the exact same as the <a href="#cl::opt"><tt>cl::opt</tt></a>
1257 class, except that the second argument is the <b>type</b> of the external
1258 storage, not a boolean value. For this class, the marker type '<tt>bool</tt>'
1259 is used to indicate that internal storage should be used.<p>
1262 <!-- _______________________________________________________________________ -->
1263 </ul><a name="cl::alias"><h4><hr size=0>The <tt>cl::alias</tt> class</h4><ul>
1265 The <tt>cl::alias</tt> class is a nontemplated class that is used to form
1266 aliases for other arguments.<p>
1269 <b>namespace</b> cl {
1274 The <a href="#cl::aliasopt"><tt>cl::aliasopt</tt></a> attribute should be used
1275 to specify which option this is an alias for. Alias arguments default to being
1276 <a href="#cl::Hidden">Hidden</a>, and use the aliased options parser to do the
1277 conversion from string to data.<p>
1280 <!-- ======================================================================= -->
1281 </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>
1282 <a name="builtinparsers">Builtin parsers
1283 </b></font></td></tr></table><ul>
1285 Parsers control how the string value taken from the command line is translated
1286 into a typed value, suitable for use in a C++ program. By default, the
1287 CommandLine library uses an instance of <tt>parser<type></tt> if the
1288 command line option specifies that it uses values of type '<tt>type</tt>'.
1289 Because of this, custom option processing is specified with specializations of
1290 the '<tt>parser</tt>' class.<p>
1292 The CommandLine library provides the following builtin parser specializations,
1293 which are sufficient for most applications. It can, however, also be extended to
1294 work with new data types and new ways of interpreting the same data. See the <a
1295 href="#customparser">Writing a Custom Parser</a> for more details on this type
1296 of library extension.<p>
1298 <li><a name="genericparser">The <b>generic <tt>parser<t></tt> parser</b>
1299 can be used to map strings values to any data type, through the use of the <a
1300 href="#cl::values">cl::values</a> property, which specifies the mapping
1301 information. The most common use of this parser is for parsing enum values,
1302 which allows you to use the CommandLine library for all of the error checking to
1303 make sure that only valid enum values are specified (as opposed to accepting
1304 arbitrary strings). Despite this, however, the generic parser class can be used
1305 for any data type.<p>
1307 <li><a name="boolparser">The <b><tt>parser<bool></tt> specialization</b>
1308 is used to convert boolean strings to a boolean value. Currently accepted
1309 strings are "<tt>true</tt>", "<tt>TRUE</tt>", "<tt>True</tt>", "<tt>1</tt>",
1310 "<tt>false</tt>", "<tt>FALSE</tt>", "<tt>False</tt>", and "<tt>0</tt>".<p>
1312 <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>
1314 <li><a name="intparser">The <b><tt>parser<int></tt> specialization</b>
1315 uses the C <tt>strtol</tt> function to parse the string input. As such, it will
1316 accept a decimal number (with an optional '+' or '-' prefix) which must start
1317 with a non-zero digit. It accepts octal numbers, which are identified with a
1318 '<tt>0</tt>' prefix digit, and hexadecimal numbers with a prefix of
1319 '<tt>0x</tt>' or '<tt>0X</tt>'.<p>
1321 <li><a name="doubleparser">The <b><tt>parser<double></tt></b> and
1322 <b><tt>parser<float></tt> specializations</b> use the standard C
1323 <tt>strtod</tt> function to convert floating point strings into floating point
1324 values. As such, a broad range of string formats is supported, including
1325 exponential notation (ex: <tt>1.7e15</tt>) and properly supports locales.
1330 <!-- *********************************************************************** -->
1331 </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>
1332 <a name="extensionguide">Extension Guide
1333 </b></font></td></tr></table><ul>
1334 <!-- *********************************************************************** -->
1336 Although the CommandLine library has a lot of functionality built into it
1337 already (as discussed previously), one of its true strengths lie in its
1338 extensibility. This section discusses how the CommandLine library works under
1339 the covers and illustrates how to do some simple, common, extensions.<p>
1342 <!-- ======================================================================= -->
1343 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0>
1344 <tr><td> </td><td width="100%"> <font color="#EEEEFF"
1345 face="Georgia,Palatino"><b> <a name="customparser">Writing a custom parser
1346 </b></font></td></tr></table><ul>
1348 One of the simplest and most common extensions is the use of a custom parser.
1349 As <a href="#builtinparsers">discussed previously</a>, parsers are the portion
1350 of the CommandLine library that turns string input from the user into a
1351 particular parsed data type, validating the input in the process.<p>
1353 There are two ways to use a new parser:<p>
1356 <li>Specialize the <a href="#genericparser"><tt>cl::parser</tt></a> template for
1357 your custom data type.<p>
1359 This approach has the advantage that users of your custom data type will
1360 automatically use your custom parser whenever they define an option with a
1361 value type of your data type. The disadvantage of this approach is that it
1362 doesn't work if your fundemental data type is something that is already
1365 <li>Write an independant class, using it explicitly from options that need
1368 This approach works well in situations where you would line to parse an
1369 option using special syntax for a not-very-special data-type. The drawback
1370 of this approach is that users of your parser have to be aware that they are
1371 using your parser, instead of the builtin ones.<p>
1375 To guide the discussion, we will discuss a custom parser that accepts file
1376 sizes, specified with an optional unit after the numeric size. For example, we
1377 would like to parse "102kb", "41M", "1G" into the appropriate integer value. In
1378 this case, the underlying data type we want to parse into is
1379 '<tt>unsigned</tt>'. We choose approach #2 above because we don't want to make
1380 this the default for all <tt>unsigned</tt> options.<p>
1382 To start out, we declare our new <tt>FileSizeParser</tt> class:<p>
1385 <b>struct</b> FileSizeParser : <b>public</b> cl::basic_parser<<b>unsigned</b>> {
1386 <i>// parse - Return true on error.</i>
1387 <b>bool</b> parse(cl::Option &O, <b>const char</b> *ArgName, <b>const</b> std::string &ArgValue,
1388 <b>unsigned</b> &Val);
1392 Our new class inherits from the <tt>cl::basic_parser</tt> template class to fill
1393 in the default, boiler plate, code for us. We give it the data type that we
1394 parse into (the last argument to the <tt>parse</tt> method so that clients of
1395 our custom parser know what object type to pass in to the parse method (here we
1396 declare that we parse into '<tt>unsigned</tt>' variables.<p>
1398 For most purposes, the only method that must be implemented in a custom parser
1399 is the <tt>parse</tt> method. The <tt>parse</tt> method is called whenever the
1400 option is invoked, passing in the option itself, the option name, the string to
1401 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>
1404 <b>bool</b> FileSizeParser::parse(cl::Option &O, <b>const char</b> *ArgName,
1405 <b>const</b> std::string &Arg, <b>unsigned</b> &Val) {
1406 <b>const char</b> *ArgStart = Arg.c_str();
1409 <i>// Parse integer part, leaving 'End' pointing to the first non-integer char</i>
1410 Val = (unsigned)strtol(ArgStart, &End, 0);
1413 <b>switch</b> (*End++) {
1414 <b>case</b> 0: <b>return</b> false; <i>// No error</i>
1415 <b>case</b> 'i': <i>// Ignore the 'i' in KiB if people use that</i>
1416 <b>case</b> 'b': <b>case</b> 'B': <i>// Ignore B suffix</i>
1419 <b>case</b> 'g': <b>case</b> 'G': Val *= 1024*1024*1024; <b>break</b>;
1420 <b>case</b> 'm': <b>case</b> 'M': Val *= 1024*1024; <b>break</b>;
1421 <b>case</b> 'k': <b>case</b> 'K': Val *= 1024; <b>break</b>;
1424 <i>// Print an error message if unrecognized character!</i>
1425 <b>return</b> O.error(": '" + Arg + "' value invalid for file size argument!");
1431 This function implements a very simple parser for the kinds of strings we are
1432 interested in. Although it has some holes (it allows "<tt>123KKK</tt>" for
1433 example), it is good enough for this example. Note that we use the option
1434 itself to print out the error message (the <tt>error</tt> method always returns
1435 true) in order to get a nice error message (shown below). Now that we have our
1436 parser class, we can use it like this:<p>
1439 <b>static</b> <a href="#cl::opt">cl::opt</a><<b>unsigned</b>, <b>false</b>, FileSizeParser>
1440 MFS(<i>"max-file-size"</i>, <a href="#cl::desc">cl::desc</a>(<i>"Maximum file size to accept"</i>),
1441 <a href="#cl::value_desc">cl::value_desc</a>("<i>size</i>"));
1444 Which adds this to the output of our program:<p>
1448 -help - display available options (--help-hidden for more)
1450 <b>-max-file-size=<size> - Maximum file size to accept</b>
1453 And we can test that our parse works correctly now (the test program just prints
1454 out the max-file-size argument value):<p>
1459 $ ./test -max-file-size=123MB
1461 $ ./test -max-file-size=3G
1463 $ ./test -max-file-size=dog
1464 -max-file-size option: 'dog' value invalid for file size argument!
1467 It looks like it works. The error message that we get is nice and helpful, and
1468 we seem to accept reasonable file sizes. This wraps up the "custom parser"
1472 <!-- ======================================================================= -->
1473 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0>
1474 <tr><td> </td><td width="100%"> <font color="#EEEEFF"
1475 face="Georgia,Palatino"><b> <a name="explotingexternal">Exploiting external
1476 storage </b></font></td></tr></table><ul>
1480 <!-- ======================================================================= -->
1481 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0>
1482 <tr><td> </td><td width="100%"> <font color="#EEEEFF"
1483 face="Georgia,Palatino"><b> <a name="dynamicopts">Dynamically adding command
1484 line options </b></font></td></tr></table><ul>
1490 <!-- *********************************************************************** -->
1492 <!-- *********************************************************************** -->
1496 <address><a href="mailto:sabre@nondot.org">Chris Lattner</a></address>
1497 <!-- Created: Tue Jan 23 15:19:28 CST 2001 -->
1498 <!-- hhmts start -->
1499 Last modified: Mon Jul 14 12:12:15 CDT 2003