Argp is an interface for parsing unix-style argument vectors. the section called “Program Arguments”.
Argp provides features unavailable in the more commonly used getopt interface. These features include automatically producing output in response to the -help and -version options, as described in the GNU coding standards. Using argp makes it less likely that programmers will neglect to implement these additional options or keep them up to date.
Argp also provides the ability to merge several independently defined option parsers into one, mediating conflicts between them and making the result appear seamless. A library can export an argp option parser that user programs might employ in conjunction with their own option parsers, resulting in less work for the user programs. Some programs may use only argument parsers exported by libraries, thereby achieving consistent and efficient option-parsing for abstractions implemented by the libraries.
The header file argp.h should be included to use argp.
The main interface to argp is the argp_parse function. In many cases, calling argp_parse is the only argument-parsing code needed in main. the section called “Program Arguments”.
error_t function>argp_parse/function> (const struct argp *argp, int argc, char **argv, unsigned flags, int *arg_index, void *input) The argp_parse function parses the arguments in argv, of length argc, using the argp parser argp. the section called “Specifying Argp Parsers”.
A value of zero is the same as a struct argpcontaining all zeros. flags is a set of flag bits that modify the parsing behavior. the section called “Flags for argp_parse”. input is passed through to the argp parser argp, and has meaning defined by argp. A typical usage is to pass a pointer to a structure which is used for specifying parameters to the parser and passing back the results.
Unless the ARGP_NO_EXIT or ARGP_NO_HELP flags are included in flags, calling argp_parse may result in the program exiting. This behavior is true if an error is detected, or when an unknown option is encountered. the section called “Program Termination”.
If arg_index is non-null, the index of the first unparsed option in argv is returned as a value.
The return value is zero for successful parsing, or an error code (the section called “Error Codes”) if an error is detected. Different argp parsers may return arbitrary error codes, but the standard error codes are: ENOMEM if a memory allocation error occurred, or EINVAL if an unknown option or option argument is encountered.
These variables make it easy for user programs to implement the -version option and provide a bug-reporting address in the -help output. These are implemented in argp by default.
const char * function>argp_program_version/function> If defined or set by the user program to a non-zero value, then a -version option is added when parsing with argp_parse, which will print the -version string followed by a newline and exit. The exception to this is if the ARGP_NO_EXIT flag is used.
const char * function>argp_program_bug_address/function> If defined or set by the user program to a non-zero value, argp_program_bug_address should point to a string that will be printed at the end of the standard output for the -help option, embedded in a sentence that says Report bugs to address..
function>argp_program_version_hook/function> If defined or set by the user program to a non-zero value, a -version option is added when parsing with arg_parse, which prints the program version and exits with a status of zero. This is not the case if the ARGP_NO_HELP flag is used. If the ARGP_NO_EXIT flag is set, the exit behavior of the program is suppressed or modified, as when the argp parser is going to be used by other programs.
It should point to a function with this type of signature:
void print-version (FILE *stream, struct argp_state *state)
the section called “Argp Parsing State ”, for an explanation of state.
This variable takes precedence over argp_program_version, and is useful if a program has version information not easily expressed in a simple string.
error_t function>argp_err_exit_status/function> This is the exit status used when argp exits due to a parsing error. If not defined or set by the user program, this defaults to: EX_USAGE from sysexits.h.
The first argument to the argp_parse function is a pointer to a struct argp, which is known as an argp parser:
function>struct argp/function> This structure specifies how to parse a given set of options and arguments, perhaps in conjunction with other argp parsers. It has the following fields:
A pointer to a vector of argp_option structures specifying which options this argp parser understands; it may be zero if there are no options at all. the section called “Specifying Options in an Argp Parser”.
A pointer to a function that defines actions for this parser; it is called for each option parsed, and at other well-defined points in the parsing process. A value of zero is the same as a pointer to a function that always returns ARGP_ERR_UNKNOWN. the section called “Argp Parser Functions”.
If non-zero, a string describing what non-option arguments are called by this parser. This is only used to print the Usage: message. If it contains newlines, the strings separated by them are considered alternative usage patterns and printed on separate lines. Lines after the first are prefixed by or: instead of Usage:.
If non-zero, a string containing extra text to be printed before and after the options in a long help message, with the two sections separated by a vertical tab ('\v', '\013') character. By convention, the documentation before the options is just a short string explaining what the program does. Documentation printed after the options describe behavior in more detail.
A pointer to a vector of argp_children structures. This pointer specifies which additional argp parsers should be combined with this one. the section called “Combining Multiple Argp Parsers”.
If non-zero, a pointer to a function that filters the output of help messages. the section called “Customizing Argp Help Output”.
If non-zero, the strings used in the argp library are translated using the domain described by this string. If zero, the current default domain is used.
Of the above group, options, parser, args_doc, and the doc fields are usually all that are needed. If an argp parser is defined as an initialized C variable, only the fields used need be specified in the initializer. The rest will default to zero due to the way C structure initialization works. This design is exploited in most argp structures; the most-used fields are grouped near the beginning, the unused fields left unspecified.
The options field in a struct argp points to a vector of struct argp_option structures, each of which specifies an option that the argp parser supports. Multiple entries may be used for a single option provided it has multiple names. This should be terminated by an entry with zero in all fields. Note that when using an initialized C array for options, writing { 0 } is enough to achieve this.
function>struct argp_option/function> This structure specifies a single option that an argp parser understands, as well as how to parse and document that option. It has the following fields:
The long name for this option, corresponding to the long option -name; this field may be zero if this option only has a short name. To specify multiple names for an option, additional entries may follow this one, with the OPTION_ALIAS flag set. the section called “Flags for Argp Options”.
The integer key provided by the current option to the option parser. If key has a value that is a printable ascii character (i.e., isascii (key) is true), it also specifies a short option -char, where char is the ascii character with the code key.
If non-zero, this is the name of an argument associated with this option, which must be provided (e.g., with the -name=value or -charvalue syntaxes), unless the OPTION_ARG_OPTIONAL flag (the section called “Flags for Argp Options”) is set, in which case it may be provided.
Flags associated with this option, some of which are referred to above. the section called “Flags for Argp Options”.
A documentation string for this option, for printing in help messages.
If both the name and key fields are zero, this string will be printed tabbed left from the normal option column, making it useful as a group header. This will be the first thing printed in its group. In this usage, it's conventional to end the string with a : character.
Group identity for this option.
In a long help message, options are sorted alphabetically within each group, and the groups presented in the order 0, 1, 2, …, n, −m, …, −2, −1.
Every entry in an options array with this field 0 will inherit the group number of the previous entry, or zero if it's the first one. If it's a group header with name and key fields both zero, the previous entry + 1 is the default. Automagic options such as -help are put into group −1.
Note that because of C structure initialization rules, this field often need not be specified, because 0 is the correct value.
The following flags may be or'd together in the flags field of a struct argp_option. These flags control various aspects of how that option is parsed or displayed in help messages:
The argument associated with this option is optional.
This option isn't displayed in any help messages.
This option is an alias for the closest previous non-alias option. This means that it will be displayed in the same help entry, and will inherit fields other than name and key from the option being aliased.
This option isn't actually an option and should be ignored by the actual option parser. It is an arbitrary section of documentation that should be displayed in much the same manner as the options. This is known as a documentation option.
If this flag is set, then the option name field is displayed unmodified (e.g., no - prefix is added) at the left-margin where a short option would normally be displayed, and this documentation string is left in it's usual place. For purposes of sorting, any leading whitespace and punctuation is ignored, unless the first non-whitespace character is -. This entry is displayed after all options, after OPTION_DOC entries with a leading -, in the same group.
This option shouldn't be included in `long' usage messages, but should still be included in other help messages. This is intended for options that are completely documented in an argp's args_doc field. the section called “Specifying Argp Parsers”. Including this option in the generic usage list would be redundant, and should be avoided.
For instance, if args_doc is "FOO BAR\n-x BLAH", and the -x option's purpose is to distinguish these two cases, -x should probably be marked OPTION_NO_USAGE.
The function pointed to by the parser field in a struct argp (the section called “Specifying Argp Parsers”) defines what actions take place in response to each option or argument parsed. It is also used as a hook, allowing a parser to perform tasks at certain other points during parsing.
Argp parser functions have the following type signature:
error_t parser (int key, char *arg, struct argp_state *state)
where the arguments are as follows:
For each option that is parsed, parser is called with a value of key from that option's key field in the option vector. the section called “Specifying Options in an Argp Parser”. parser is also called at other times with special reserved keys, such as ARGP_KEY_ARG for non-option arguments. the section called “Special Keys for Argp Parser Functions”.
If key is an option, arg is its given value. This defaults to zero if no value is specified. Only options that have a non-zero arg field can ever have a value. These must always have a value unless the OPTION_ARG_OPTIONAL flag is specified. If the input being parsed specifies a value for an option that doesn't allow one, an error results before parser ever gets called.
If key is ARGP_KEY_ARG, arg is a non-option argument. Other special keys always have a zero arg.
state points to a struct argp_state, containing useful information about the current parsing state for use by parser. the section called “Argp Parsing State ”.
When parser is called, it should perform whatever action is appropriate for key, and return 0 for success, ARGP_ERR_UNKNOWN if the value of key is not handled by this parser function, or a unix error code if a real error occurred. the section called “Error Codes”.
int function>ARGP_ERR_UNKNOWN/function> Argp parser functions should return ARGP_ERR_UNKNOWN for any key value they do not recognize, or for non-option arguments (key == ARGP_KEY_ARG) that they are not equipped to handle.
A typical parser function uses a switch statement on key:
error_t parse_opt (int key, char *arg, struct argp_state *state) { switch (key) { case option_key: action break; … default: return ARGP_ERR_UNKNOWN; } return 0; }
In addition to key values corresponding to user options, the key argument to argp parser functions may have a number of other special values. In the following example arg and state refer to parser function arguments. the section called “Argp Parser Functions”.
This is not an option at all, but rather a command line argument, whose value is pointed to by arg.
When there are multiple parser functions in play due to argp parsers being combined, it's impossible to know which one will handle a specific argument. Each is called until one returns 0 or an error other than ARGP_ERR_UNKNOWN; if an argument is not handled, argp_parse immediately returns success, without parsing any more arguments.
Once a parser function returns success for this key, that fact is recorded, and the ARGP_KEY_NO_ARGS case won't be used. However, if while processing the argument a parser function decrements the next field of its state argument, the option won't be considered processed; this is to allow you to actually modify the argument, perhaps into an option, and have it processed again.
If a parser function returns ARGP_ERR_UNKNOWN for ARGP_KEY_ARG, it is immediately called again with the key ARGP_KEY_ARGS, which has a similar meaning, but is slightly more convenient for consuming all remaining arguments. arg is 0, and the tail of the argument vector may be found at state-argv + state-next. If success is returned for this key, and state-next is unchanged, all remaining arguments are considered to have been consumed. Otherwise, the amount by which state-next has been adjusted indicates how many were used. Here's an example that uses both, for different args:
... case ARGP_KEY_ARG: if (state-arg_num == 0) /* First argument */ first_arg = arg; else /* Let the next case parse it. */ return ARGP_KEY_UNKNOWN; break; case ARGP_KEY_ARGS: remaining_args = state-argv + state-next; num_remaining_args = state-argc - state-next; break;
This indicates that there are no more command line arguments. Parser functions are called in a different order, children first. This allows each parser to clean up its state for the parent.
Because it's common to do some special processing if there aren't any non-option args, parser functions are called with this key if they didn't successfully process any non-option arguments. This is called just before ARGP_KEY_END, where more general validity checks on previously parsed arguments take place.
This is passed in before any parsing is done. Afterwards, the values of each element of the child_input field of state, if any, are copied to each child's state to be the initial value of the input when their parsers are called.
Passed in when parsing has successfully been completed, even if arguments remain.
Passed in if an error has occurred and parsing is terminated. In this case a call with a key of ARGP_KEY_SUCCESS is never made.
The final key ever seen by any parser, even after ARGP_KEY_SUCCESS and ARGP_KEY_ERROR. Any resources allocated by ARGP_KEY_INIT may be freed here. At times, certain resources allocated are to be returned to the caller after a successful parse. In that case, those particular resources can be freed in the ARGP_KEY_ERROR case.
In all cases, ARGP_KEY_INIT is the first key seen by parser functions, and ARGP_KEY_FINI the last, unless an error was returned by the parser for ARGP_KEY_INIT. Other keys can occur in one the following orders. opt refers to an arbitrary option key:
The arguments being parsed did not contain any non-option arguments.
All non-option arguments were successfully handled by a parser function. There may be multiple parser functions if multiple argp parsers were combined.
Some non-option argument went unrecognized.
This occurs when every parser function returns ARGP_KEY_UNKNOWN for an argument, in which case parsing stops at that argument if arg_index is a null pointer. Otherwise an error occurs.
In all cases, if a non-null value for arg_index gets passed to argp_parse, the index of the first unparsed command-line argument is passed back in that value.
If an error occurs and is either detected by argp or because a parser function returned an error value, each parser is called with ARGP_KEY_ERROR. No further calls are made, except the final call with ARGP_KEY_FINI.
Argp provides a number of functions available to the user of argp (the section called “Argp Parser Functions”), mostly for producing error messages. These take as their first argument the state argument to the parser function. the section called “Argp Parsing State ”.
void function>argp_usage/function> (const struct argp_state *state) Outputs the standard usage message for the argp parser referred to by state to state-err_stream and terminate the program with exit (argp_err_exit_status). the section called “Argp Global Variables”.
void function>argp_error/function> (const struct argp_state *state, const char *fmt, …) Prints the printf format string fmt and following args, preceded by the program name and :, and followed by a Try … -help message, and terminates the program with an exit status of argp_err_exit_status. the section called “Argp Global Variables”.
void function>argp_failure/function> (const struct argp_state *state, int status, int errnum, const char *fmt, …) Similar to the standard gnu error-reporting function error, this prints the program name and :, the printf format string fmt, and the appropriate following args. If it is non-zero, the standard unix error text for errnum is printed. If status is non-zero, it terminates the program with that value as its exit status.
The difference between argp_failure and argp_error is that argp_error is for parsing errors, whereas argp_failure is for other problems that occur during parsing but don't reflect a syntactic problem with the input, such as illegal values for options, bad phase of the moon, etc.
void function>argp_state_help/function> (const struct argp_state *state, FILE *stream, unsigned flags) Outputs a help message for the argp parser referred to by state, to stream. The flags argument determines what sort of help message is produced. the section called “Flags for the argp_helpFunction”.
Error output is sent to state-err_stream, and the program name printed is state-name.
The output or program termination behavior of these functions may be suppressed if the ARGP_NO_EXIT or ARGP_NO_ERRS flags are passed to argp_parse. the section called “Flags for argp_parse”.
This behavior is useful if an argp parser is exported for use by other programs (e.g., by a library), and may be used in a context where it is not desirable to terminate the program in response to parsing errors. In argp parsers intended for such general use, and for the case where the program doesn't terminate, calls to any of these functions should be followed by code that returns the appropriate error code:
if (bad argument syntax) { argp_usage (state); return EINVAL; }
If a parser function will only be used when ARGP_NO_EXIT is not set, the return may be omitted.
The third argument to argp parser functions (the section called “Argp Parser Functions”) is a pointer to a struct argp_state, which contains information about the state of the option parsing.
function>struct argp_state/function> This structure has the following fields, which may be modified as noted:
The top level argp parser being parsed. Note that this is often not the same struct argp passed into argp_parse by the invoking program. the section called “Parsing Program Options with Argp”. It is an internal argp parser that contains options implemented by argp_parse itself, such as -help.
The argument vector being parsed. This may be modified.
The index in argv of the next argument to be parsed. This may be modified.
One way to consume all remaining arguments in the input is to set state-next = state-argc, perhaps after recording the value of the next field to find the consumed arguments. The current option can be re-parsed immediately by decrementing this field, then modifying state-argv[state-next] to reflect the option that should be reexamined.
The flags supplied to argp_parse. These may be modified, although some flags may only take effect when argp_parse is first invoked. the section called “Flags for argp_parse”.
While calling a parsing function with the key argument ARGP_KEY_ARG, this represents the number of the current arg, starting at 0. It is incremented after each ARGP_KEY_ARG call returns. At all other times, this is the number of ARGP_KEY_ARG arguments that have been processed.
If non-zero, the index in argv of the first argument following a special - argument. This prevents anything that follows from being interpreted as an option. It is only set after argument parsing has proceeded past this point.
An arbitrary pointer passed in from the caller of argp_parse, in the input argument.
These are values that will be passed to child parsers. This vector will be the same length as the number of children in the current parser. Each child parser will be given the value of state-child_inputs[i] as itsstate-input field, where i is the index of the child in the this parser's children field. the section called “Combining Multiple Argp Parsers”.
For the parser function's use. Initialized to 0, but otherwise ignored by argp.
The name used when printing messages. This is initialized to argv[0], or program_invocation_name if argv[0] is unavailable.
The stdio streams used when argp prints. Error messages are printed to err_stream, all other output, such as -help output) to out_stream. These are initialized to stderr and stdout respectively. the section called “Standard Streams”.
Private, for use by the argp implementation.
The children field in a struct argp enables other argp parsers to be combined with the referencing one for the parsing of a single set of arguments. This field should point to a vector of struct argp_child, which is terminated by an entry having a value of zero in the argp field.
Where conflicts between combined parsers arise, as when two specify an option with the same name, the parser conflicts are resolved in favor of the parent argp parser(s), or the earlier of the argp parsers in the list of children.
function>struct argp_child/function> An entry in the list of subsidiary argp parsers pointed to by the children field in a struct argp. The fields are as follows:
The child argp parser, or zero to end of the list.
Flags for this child.
If non-zero, this is an optional header to be printed within help output before the child options. As a side-effect, a non-zero value forces the child options to be grouped together. To achieve this effect without actually printing a header string, use a value of "". As with header strings specified in an option entry, the conventional value of the last character is :. the section called “Specifying Options in an Argp Parser”.
This is where the child options are grouped relative to the other `consolidated' options in the parent argp parser. The values are the same as the group field in struct argp_option. the section called “Specifying Options in an Argp Parser”. All child-groupings follow parent options at a particular group level. If both this field and header are zero, then the child's options aren't grouped together, they are merged with parent options at the parent option group level.
The default behavior of argp_parse is designed to be convenient for the most common case of parsing program command line argument. To modify these defaults, the following flags may be or'd together in the flags argument to argp_parse:
Don't ignore the first element of the argv argument to argp_parse. Unless ARGP_NO_ERRS is set, the first element of the argument vector is skipped for option parsing purposes, as it corresponds to the program name in a command line.
Don't print error messages for unknown options to stderr; unless this flag is set, ARGP_PARSE_ARGV0 is ignored, as argv[0] is used as the program name in the error messages. This flag implies ARGP_NO_EXIT. This is based on the assumption that silent exiting upon errors is bad behavior.
Don't parse any non-option args. Normally these are parsed by calling the parse functions with a key of ARGP_KEY_ARG, the actual argument being the value. This flag needn't normally be set, as the default behavior is to stop parsing as soon as an argument fails to be parsed. the section called “Argp Parser Functions”.
Parse options and arguments in the same order they occur on the command line. Normally they're rearranged so that all options come first.
Don't provide the standard long option -help, which ordinarily causes usage and option help information to be output to stdout and exit (0).
Don't exit on errors, although they may still result in error messages.
Use the gnu getopt `long-only' rules for parsing arguments. This allows long-options to be recognized with only a single - (i.e. -help). This results in a less useful interface, and its use is discouraged as it conflicts with the way most GNU programs work as well as the GNU coding standards.
Turns off any message-printing/exiting options, specifically ARGP_NO_EXIT, ARGP_NO_ERRS, and ARGP_NO_HELP.
The help_filter field in a struct argp is a pointer to a function that filters the text of help messages before displaying them. They have a function signature like:
char *help-filter (int key, const char *text, void *input)
Where key is either a key from an option, in which case text is that option's help text. the section called “Specifying Options in an Argp Parser”. Alternately, one of the special keys with names beginning with ARGP_KEY_HELP_ might be used, describing which other help text text will contain. the section called “Special Keys for Argp Help Filter Functions”.
The function should return either text if it remains as-is, or a replacement string allocated using malloc. This will be either be freed by argp or zero, which prints nothing. The value of text is supplied after any translation has been done, so if any of the replacement text needs translation, it will be done by the filter function. input is either the input supplied to argp_parse or it is zero, if argp_help was called directly by the user.
The following special values may be passed to an argp help filter function as the first argument in addition to key values for user options. They specify which help text the text argument contains:
The help text preceding options.
The help text following options.
The option header string.
This is used after all other documentation; text is zero for this key.
The explanatory note printed when duplicate option arguments have been suppressed.
The argument doc string; formally the args_doc field from the argp parser. the section called “Specifying Argp Parsers”.
Normally programs using argp need not be written with particular printing argument-usage-type help messages in mind as the standard -help option is handled automatically by argp. Typical error cases can be handled using argp_usage and argp_error. the section called “Functions For Use in Argp Parsers”. However, if it's desirable to print a help message in some context other than parsing the program options, argp offers the argp_help interface.
void function>argp_help/function> (const struct argp *argp, FILE *stream, unsigned flags, char *name) This outputs a help message for the argp parser argp to stream. The type of messages printed will be determined by flags.
Any options such as -help that are implemented automatically by argp itself will not be present in the help output; for this reason it is best to use argp_state_help if calling from within an argp parser function. the section called “Functions For Use in Argp Parsers”.
When calling argp_help (the section called “The argp_helpFunction”) or argp_state_help (the section called “Functions For Use in Argp Parsers”) the exact output is determined by the flags argument. This should consist of any of the following flags, or'd together:
A unix Usage: message that explicitly lists all options.
A unix Usage: message that displays an appropriate placeholder to indicate where the options go; useful for showing the non-option argument syntax.
A Try … for more help message; … contains the program name and -help.
A verbose option help message that gives each option available along with its documentation string.
The part of the argp parser doc string preceding the verbose option help.
The part of the argp parser doc string that following the verbose option help.
(ARGP_HELP_PRE_DOC | ARGP_HELP_POST_DOC)
A message that prints where to report bugs for this program, if the argp_program_bug_address variable contains this information.
This will modify any output to reflect the ARGP_LONG_ONLY mode.
The following flags are only understood when used with argp_state_help. They control whether the function returns after printing its output, or terminates the program:
This will terminate the program with exit (argp_err_exit_status).
This will terminate the program with exit (0).
The following flags are combinations of the basic flags for printing standard messages:
Assuming that an error message for a parsing error has printed, this prints a message on how to get help, and terminates the program with an error.
This prints a standard usage message and terminates the program with an error. This is used when no other specific error messages are appropriate or available.
This prints the standard response for a -help option, and terminates the program successfully.
These example programs demonstrate the basic usage of argp.
This is perhaps the smallest program possible that uses argp. It won't do much except give an error messages and exit when there are any arguments, and prints a rather pointless message for -help.
/* Argp example #1 -- a minimal program using argp */ /* This is (probably) the smallest possible program that uses argp. It won't do much except give an error messages and exit when there are any arguments, and print a (rather pointless) messages for --help. */ #include argp.h int main (int argc, char **argv) { argp_parse (0, argc, argv, 0, 0, 0); exit (0); }
This program doesn't use any options or arguments, it uses argp to be compliant with the GNU standard command line format.
In addition to giving no arguments and implementing a -help option, this example has a -version option, which will put the given documentation string and bug address in the -help output, as per GNU standards.
The variable argp contains the argument parser specification. Adding fields to this structure is the way most parameters are passed to argp_parse. The first three fields are normally used, but they are not in this small program. There are also two global variables that argp can use defined here, argp_program_version and argp_program_bug_address. They are considered global variables because they will almost always be constant for a given program, even if they use different argument parsers for various tasks.
/* Argp example #2 -- a pretty minimal program using argp */ /* This program doesn't use any options or arguments, but uses argp to be compliant with the GNU standard command line format. In addition to making sure no arguments are given, and implementing a --help option, this example will have a --version option, and will put the given documentation string and bug address in the --help output, as per GNU standards. The variable ARGP contains the argument parser specification; adding fields to this structure is the way most parameters are passed to argp_parse (the first three fields are usually used, but not in this small program). There are also two global variables that argp knows about defined here, ARGP_PROGRAM_VERSION and ARGP_PROGRAM_BUG_ADDRESS (they are global variables becuase they will almost always be constant for a given program, even if it uses different argument parsers for various tasks). */ #include argp.h const char *argp_program_version = "argp-ex2 1.0"; const char *argp_program_bug_address = "bug-gnu-utils@gnu.org"; /* Program documentation. */ static char doc[] = "Argp example #2 -- a pretty minimal program using argp"; /* Our argument parser. The options, parser, and args_doc fields are zero because we have neither options or arguments; doc and argp_program_bug_address will be used in the output for --help, and the --version option will print out argp_program_version. */ static struct argp argp = { 0, 0, 0, doc }; int main (int argc, char **argv) { argp_parse (argp, argc, argv, 0, 0, 0); exit (0); }
This program uses the same features as example 2, adding user options and arguments.
We now use the first four fields in argp (the section called “Specifying Argp Parsers”) and specify parse_opt as the parser function. the section called “Argp Parser Functions”.
Note that in this example, main uses a structure to communicate with the parse_opt function, a pointer to which it passes in the input argument to argp_parse. the section called “Parsing Program Options with Argp”. It is retrieved by parse_opt through the input field in its state argument. the section called “Argp Parsing State ”. Of course, it's also possible to use global variables instead, but using a structure like this is somewhat more flexible and clean.
/* Argp example #3 -- a program with options and arguments using argp */ /* This program uses the same features as example 2, and uses options and arguments. We now use the first four fields in ARGP, so here's a description of them: OPTIONS -- A pointer to a vector of struct argp_option (see below) PARSER -- A function to parse a single option, called by argp ARGS_DOC -- A string describing how the non-option arguments should look DOC -- A descriptive string about this program; if it contains a vertical tab character (\v), the part after it will be printed *following* the options The function PARSER takes the following arguments: KEY -- An integer specifying which option this is (taken from the KEY field in each struct argp_option), or a special key specifying something else; the only special keys we use here are ARGP_KEY_ARG, meaning a non-option argument, and ARGP_KEY_END, meaning that all arguments have been parsed ARG -- For an option KEY, the string value of its argument, or NULL if it has none STATE-- A pointer to a struct argp_state, containing various useful information about the parsing state; used here are the INPUT field, which reflects the INPUT argument to argp_parse, and the ARG_NUM field, which is the number of the current non-option argument being parsed It should return either 0, meaning success, ARGP_ERR_UNKNOWN, meaning the given KEY wasn't recognized, or an errno value indicating some other error. Note that in this example, main uses a structure to communicate with the parse_opt function, a pointer to which it passes in the INPUT argument to argp_parse. Of course, it's also possible to use global variables instead, but this is somewhat more flexible. The OPTIONS field contains a pointer to a vector of struct argp_option's; that structure has the following fields (if you assign your option structures using array initialization like this example, unspecified fields will be defaulted to 0, and need not be specified): NAME -- The name of this option's long option (may be zero) KEY -- The KEY to pass to the PARSER function when parsing this option, *and* the name of this option's short option, if it is a printable ascii character ARG -- The name of this option's argument, if any FLAGS -- Flags describing this option; some of them are: OPTION_ARG_OPTIONAL -- The argument to this option is optional OPTION_ALIAS -- This option is an alias for the previous option OPTION_HIDDEN -- Don't show this option in --help output DOC -- A documentation string for this option, shown in --help output An options vector should be terminated by an option with all fields zero. */ #include argp.h const char *argp_program_version = "argp-ex3 1.0"; const char *argp_program_bug_address = "bug-gnu-utils@gnu.org"; /* Program documentation. */ static char doc[] = "Argp example #3 -- a program with options and arguments using argp"; /* A description of the arguments we accept. */ static char args_doc[] = "ARG1 ARG2"; /* The options we understand. */ static struct argp_option options[] = { {"verbose", 'v', 0, 0, "Produce verbose output" }, {"quiet", 'q', 0, 0, "Don't produce any output" }, {"silent", 's', 0, OPTION_ALIAS }, {"output", 'o', "FILE", 0, "Output to FILE instead of standard output" }, { 0 } }; /* Used by main to communicate with parse_opt. */ struct arguments { char *args[2]; /* arg1 arg2 */ int silent, verbose; char *output_file; }; /* Parse a single option. */ static error_t parse_opt (int key, char *arg, struct argp_state *state) { /* Get the input argument from argp_parse, which we know is a pointer to our arguments structure. */ struct arguments *arguments = state-input; switch (key) { case 'q': case 's': arguments-silent = 1; break; case 'v': arguments-verbose = 1; break; case 'o': arguments-output_file = arg; break; case ARGP_KEY_ARG: if (state-arg_num = 2) /* Too many arguments. */ argp_usage (state); arguments-args[state-arg_num] = arg; break; case ARGP_KEY_END: if (state-arg_num 2) /* Not enough arguments. */ argp_usage (state); break; default: return ARGP_ERR_UNKNOWN; } return 0; } /* Our argp parser. */ static struct argp argp = { options, parse_opt, args_doc, doc }; int main (int argc, char **argv) { struct arguments arguments; /* Default values. */ arguments.silent = 0; arguments.verbose = 0; arguments.output_file = "-"; /* Parse our arguments; every option seen by parse_opt will be reflected in arguments. */ argp_parse (argp, argc, argv, 0, 0, arguments); printf ("ARG1 = %s\nARG2 = %s\nOUTPUT_FILE = %s\n" "VERBOSE = %s\nSILENT = %s\n", arguments.args[0], arguments.args[1], arguments.output_file, arguments.verbose ? "yes" : "no", arguments.silent ? "yes" : "no"); exit (0); }
This program uses the same features as example 3, but has more options, and presents more structure in the -help output. It also illustrates how you can `steal' the remainder of the input arguments past a certain point for programs that accept a list of items. It also illustrates the key value ARGP_KEY_NO_ARGS, which is only given if no non-option arguments were supplied to the program. the section called “Special Keys for Argp Parser Functions”.
For structuring help output, two features are used: headers and a two part option string. The headers are entries in the options vector. the section called “Specifying Options in an Argp Parser”. The first four fields are zero. The two part documentation string are in the variable doc, which allows documentation both before and after the options. the section called “Specifying Argp Parsers”, the two parts of doc are separated by a vertical-tab character ('\v', or '\013'). By convention, the documentation before the options is a short string stating what the program does, and after any options it is longer, describing the behavior in more detail. All documentation strings are automatically filled for output, although newlines may be included to force a line break at a particular point. In addition, documentation strings are passed to the gettext function, for possible translation into the current locale.
/* Argp example #4 -- a program with somewhat more complicated options */
/* This program uses the same features as example 3, but has more
options, and somewhat more structure in the -help output. It
also shows how you can `steal' the remainder of the input
arguments past a certain point, for programs that accept a
list of items. It also shows the special argp KEY value
ARGP_KEY_NO_ARGS, which is only given if no non-option
arguments were supplied to the program.
For structuring the help output, two features are used,
*headers* which are entries in the options vector with the
first four fields being zero, and a two part documentation
string (in the variable DOC), which allows documentation both
before and after the options; the two parts of DOC are
separated by a vertical-tab character ('\v', or '\013'). By
convention, the documentation before the options is just a
short string saying what the program does, and that afterwards
is longer, describing the behavior in more detail. All
documentation strings are automatically filled for output,
although newlines may be included to force a line break at a
particular point. All documentation strings are also passed to
the `gettext' function, for possible translation into the
current locale. */
#include stdlib.h
#include error.h
#include argp.h
const char *argp_program_version =
"argp-ex4 1.0";
const char *argp_program_bug_address =
"bug-gnu-utils@prep.ai.mit.edu";
/* Program documentation. */
static char doc[] =
"Argp example #4 -- a program with somewhat more complicated\
options\
\vThis part of the documentation comes *after* the options;\
note that the text is automatically filled, but it's possible\
to force a line-break, e.g.\n-- here.";
/* A description of the arguments we accept. */
static char args_doc[] = "ARG1 [STRING...]";
/* Keys for options without short-options. */
#define OPT_ABORT 1 /* --abort */
/* The options we understand. */
static struct argp_option options[] = {
{"verbose", 'v', 0, 0, "Produce verbose output" },
{"quiet", 'q', 0, 0, "Don't produce any output" },
{"silent", 's', 0, OPTION_ALIAS },
{"output", 'o', "FILE", 0,
"Output to FILE instead of standard output" },
{0,0,0,0, "The following options should be grouped together:" },
{"repeat", 'r', "COUNT", OPTION_ARG_OPTIONAL,
"Repeat the output COUNT (default 10) times"},
{"abort", OPT_ABORT, 0, 0, "Abort before showing any output"},
{ 0 }
};
/* Used by main to communicate with parse_opt. */
struct arguments
{
char *arg1; /* arg1 */
char **strings; /* [string…] */
int silent, verbose, abort; /* -s, -v, --abort */
char *output_file; /* file arg to --output */
int repeat_count; /* count arg to --repeat */
};
/* Parse a single option. */
static error_t
parse_opt (int key, char *arg, struct argp_state *state)
{
/* Get the input argument from argp_parse, which we
know is a pointer to our arguments structure. */
struct arguments *arguments = state-input;
switch (key)
{
case 'q': case 's':
arguments-silent = 1;
break;
case 'v':
arguments-verbose = 1;
break;
case 'o':
arguments-output_file = arg;
break;
case 'r':
arguments-repeat_count = arg ? atoi (arg) : 10;
break;
case OPT_ABORT:
arguments-abort = 1;
break;
case ARGP_KEY_NO_ARGS:
argp_usage (state);
case ARGP_KEY_ARG:
/* Here we know that state-arg_num == 0, since we
force argument parsing to end before any more arguments can
get here. */
arguments-arg1 = arg;
/* Now we consume all the rest of the arguments.
state-next is the index in state-argv of the
next argument to be parsed, which is the first string
we're interested in, so we can just use
state-argv[state-next] as the value for
arguments-strings.
In addition, by setting state-next to the end
of the arguments, we can force argp to stop parsing here and
return. */
arguments-strings = state-argv[state-next];
state-next = state-argc;
break;
default:
return ARGP_ERR_UNKNOWN;
}
return 0;
}
/* Our argp parser. */
static struct argp argp = { options, parse_opt, args_doc, doc };
int main (int argc, char **argv)
{
int i, j;
struct arguments arguments;
/* Default values. */
arguments.silent = 0;
arguments.verbose = 0;
arguments.output_file = "-";
arguments.repeat_count = 1;
arguments.abort = 0;
/* Parse our arguments; every option seen by parse_opt will be
reflected in arguments. */
argp_parse (argp, argc, argv, 0, 0, arguments);
if (arguments.abort)
error (10, 0, "ABORTED");
for (i = 0; i arguments.repeat_count; i++)
{
printf ("ARG1 = %s\n", arguments.arg1);
printf ("STRINGS = ");
for (j = 0; arguments.strings[j]; j++)
printf (j == 0 ? "%s" : ", %s", arguments.strings[j]);
printf ("\n");
printf ("OUTPUT_FILE = %s\nVERBOSE = %s\nSILENT = %s\n",
arguments.output_file,
arguments.verbose ? "yes" : "no",
arguments.silent ? "yes" : "no");
}
exit (0);
}
The formatting of argp -help output may be controlled to some extent by a program's users, by setting the ARGP_HELP_FMT environment variable to a comma-separated list of tokens. Whitespace is ignored:
These turn duplicate-argument-mode on or off. In duplicate argument mode, if an option that accepts an argument has multiple names, the argument is shown for each name. Otherwise, it is only shown for the first long option. A note is subsequently printed so the user knows that it applies to other names as well. The default is no-dup-args, which is less consistent, but prettier.
These will enable or disable the note informing the user of suppressed option argument duplication. The default is dup-args-note.
This prints the first short option in column n. The default is 2.
This prints the first long option in column n. The default is 6.
This prints `documentation options' (the section called “Flags for Argp Options”) in column n. The default is 2.
This prints the documentation for options starting in column n. The default is 29.
This will indent the group headers that document groups of options to column n. The default is 1.
This will indent continuation lines in Usage: messages to column n. The default is 12.
This will word wrap help output at or before column n. The default is 79.
Having a single level of options is sometimes not enough. There might be too many options which have to be available or a set of options is closely related.
For this case some programs use suboptions. One of the most prominent programs is certainly mount(8). The -o option take one argument which itself is a comma separated list of options. To ease the programming of code like this the function getsubopt is available.
int function>getsubopt/function> (char **optionp, const char* const *tokens, char **valuep) The optionp parameter must be a pointer to a variable containing the address of the string to process. When the function returns the reference is updated to point to the next suboption or to the terminating \0 character if there is no more suboption available.
The tokens parameter references an array of strings containing the known suboptions. All strings must be \0 terminated and to mark the end a null pointer must be stored. When getsubopt finds a possible legal suboption it compares it with all strings available in the tokens array and returns the index in the string as the indicator.
In case the suboption has an associated value introduced by a = character, a pointer to the value is returned in valuep. The string is \0 terminated. If no argument is available valuep is set to the null pointer. By doing this the caller can check whether a necessary value is given or whether no unexpected value is present.
In case the next suboption in the string is not mentioned in the tokens array the starting address of the suboption including a possible value is returned in valuep and the return value of the function is -1.
The code which might appear in the mount(8) program is a perfect example of the use of getsubopt:
#include stdio.h #include stdlib.h #include unistd.h int do_all; const char *type; int read_size; int write_size; int read_only; enum { RO_OPTION = 0, RW_OPTION, READ_SIZE_OPTION, WRITE_SIZE_OPTION, THE_END }; const char *mount_opts[] = { [RO_OPTION] = "ro", [RW_OPTION] = "rw", [READ_SIZE_OPTION] = "rsize", [WRITE_SIZE_OPTION] = "wsize", [THE_END] = NULL }; int main (int argc, char *argv[]) { char *subopts, *value; int opt; while ((opt = getopt (argc, argv, "at:o:")) != -1) switch (opt) { case 'a': do_all = 1; break; case 't': type = optarg; break; case 'o': subopts = optarg; while (*subopts != '\0') switch (getsubopt (subopts, mount_opts, value)) { case RO_OPTION: read_only = 1; break; case RW_OPTION: read_only = 0; break; case READ_SIZE_OPTION: if (value == NULL) abort (); read_size = atoi (value); break; case WRITE_SIZE_OPTION: if (value == NULL) abort (); write_size = atoi (value); break; default: /* Unknown suboption. */ printf ("Unknown suboption `%s'\n", value); break; } break; default: abort (); } /* Do the real work. */ return 0; }