Go back to the main page.
Go back to the "extra" page.

Proposal for updating shell standards

2008-12-23
(you could probably add on the "semantic" label here).

This is another one of those ideas that everybody has been thinking about, but hasn't been written down yet.

Everyone writes shell software that allows command line arguments, usually encoded in the ARGV array. When the arguments are wrong, you, as the programmer, are kind enough to encode some manual page information to help people understand what the possible arguments are. This also goes in the MAN pages, too. Then, there's some output that the program produces, to be pipelined into something else using the conventional shell practices like the | or > and so on to control where stdin and stdout are pointing to.

Admittedly, the quick "print \"This is how you use the program:\n\n --help: display this help information...\n\n\"; " statements are hardly as useful as we could make them. An alternative concept is that of "semantic shelling" (sounds fancy).

What should be different?
What could this allow?
  1. "Search all installed programs for those that take PDF input and give me HTML output."
  2. "Find me a program that can convert this dataset in format A into format B for use with program C."
  3. "Construct me a pipeline for doing some ridiculously complicated set of transformations on data."
Where should this programming effort take place?



See the 2009 debian discussions on the debian-devel mailing list.
To make a simple interoperable system of standards, split all programs until they do one thing and one thing only. Then make a wrapper for that one thing, specifying input MIME-type and output MIME type, and then where the output will be, either through STDIO or STDOUT or to a particular file at some point in the local current directory, etc. Also a textual description of what the current 'wrapper' is for. Also, the actual mapping to the real way to call the program (i.e., you might have upwards of 200 different wrappers just for wget because of all of the options and combinations (but you shouldn't- if you have a need for all of those options, you really should read the man pages, this is more for quick and dirty use of programs)), kind of like filling out a template with variables which this 'wrapper interface' manages.

IOT for "echo"
in: text/*
out: text/*
outwhere: STDIO
useage: echo $in
description: Spits out the information to the screen.


That's a simple way of dealing with all of this. Some questions though: how do you specify STDIO versus an output file? Some programs allow you to specify --output-file=blah, while others only work on STDIO, and either way, a proper wrapper should be able to handle either of those situations and redirect the output and such to where the user wants, as long as this description properly describes how the program is going to behave.

Anybody else see the similarities to keeping method/function signatures in various programming languages? Not much of a difference here.

int main (int argc, char *argv[]) <--- ISO C standard.



What if we had one file per option for a program? In this file, there would be a list of the other options that it is incompatible with, a list of those options that it must be used with, a list of those options that it must come before, a list of those options that it must come after, a MIME-type on what information that this flag is to be given (or null), whether or not to use an "=" symbol after the option before specifying the information, whether or not to use one dash or two dashes, and a description of what this option does. Uh, maybe also information about what program it is supposed to be used for.

http://www.gnu.org/software/gengetopt/gengetopt.html#Basic-Usage

2 Basic Usage

The command line options, which have to be handled by gengetopt generated function, are specified in a file (typically with .ggo extension). This file consists of sentences with the formats shown below (these sentences are allowed to span more than one line). Statements in {} are optional (the option sentences need not to be given in separate lines):

     package "<packname>"
     version "<version>"
     purpose "<purpose>"
     usage "<usage>"
     description "<description>"
     
     args "<command line options>"
     
     option <long> <short> "<desc>"
         {details="<detailed description>"}
         {argtype} {typestr="<type descr>"}
         {values="<value1>","<value2>",...}
         {default="<default value>"}
         {dependon="<other option>"}
         {required} {argoptional} {multiple}
         {hidden}
     
     option <long> <short> "<desc>" flag <on/off>
     
     section "section name" {sectiondesc="optional section description"}
     
     text "a textual sentence"

Where:

package
This has the precedence over PACKAGE generated by autoconf. Optional.
version
This has the precedence over VERSION generated by autoconf. Optional.
purpose
What the program does (even on more than one line), it will be printed with the help, before the usage string. Optional.
usage
The “Usage” string that will be printed with the help5. If not specified, it will be generated automatically. Optional.
description
The “Description” string that will be printed with the help6, after the usage string. Optional.
args
With args7 you can specify options that will be added to the command line options of gengetopt itself. For instance, if you always run gengetopt on your input file with the options --no-handle-error --string-parser -u, you can add these options in the input file like this:
          args "--no-handle-error --string-parser -u"
     

and remove those recurrent options from the command line. Optional.

long
The long option, a double quoted string with upper and lower case characters, digits, a dash (-) and a dot (.). No spaces allowed. The name of the variables generated to store arguments (see later in this section) are long options converted to be legal C variable names. This means that . and - are both replaced by _.


short
The short option, a single upper or lower case char, or a digit. If a - is specified, then no short option is considered for the long option (thus long options with no associated short options are allowed). Since version 2.22 you can also specify ? as the short option.


desc
This description will be printed during the output of --help. Wrapping will be automatically performed.
details
This is an extended description string for the option that will be printed (after the option) during the output of --detailed-help8, which will be automatically generated. Thus, these further details will NOT be printed with --help. Wrapping will be automatically performed. Optional.


argtype
string, int, short, long, float, double, longdouble or longlong. If the option is an enumerated one (see Options with enumerated values) the type can also be enum. If no type is specified the option does not accept an argument.


typestr
a description for the type of the values for the option. This will be used during the output of --help (e.g., "filename" instead of simply STRING, or "portnumber" instead of simply INT).


values
a list of strings containing all the possible values that can be passed to the option. If not specified, the type is considered string9. For this kind of options, the type can also be enum. More on this feature can be found in Options with enumerated values.


default
an optional default value for the option. The value must always be specified as a double quoted string.


dependon
this option depends on another option (whose long name description is specified). If this option is given at command line but not the option it depends on, an error will be generated.


required
required or optional. This specifies whether such option must be given at each program invocation. These keywords were introduced in release 2.17. Before, you had to use the keywords yes or no. You can still use these keywords but their use is not advised since they are not much explicative.

If not specified, an option is considered mandatory; if you do not want this behavior, you can require that by default options are considered optional, by using the command line option --default-optional10.


argoptional
If this flag is specified then this option has an argument that is optional. In this case, when you specify the argument at command line, please use = in case you use a long option, and avoid spaces if you use short option. For instance, if the option with optional argument is -B|--bar, use the following command line syntax: -B15 or --bar=15, and NOT the following one -B 15 nor --bar 15.

By using this specification together with default you can obtain an option that even if not explicitly specified will have the default value, and if it is specified without an argument it will have, again, the default value.


multiple
If this flag is specified then this option can be specified more than once at command line; all the values for this option are stored in an array. You can also specify the number of occurrences that a multiple option must be specified. Notice that this is independent from the required flag. See Multiple Options.


hidden
If an option is “hidden” it will not appear in the output of --help but it can still be specified at command line11. In case hidden options are used, the command line option --full-help will also be generated. This will print also the hidden options12. If there's an option with details, then also --detailed-help13 will be automatically generated; if one then specifies --detailed-help also hidden options will be printed (besides the details for options).


on/off
on or off. This is the state of the flag when the program starts. If user specifies the option, the flag toggles.

For strings (delimited by ") the following convention is adopted14: a string spanning more than one line will be interpreted with the corresponding line breaks; if the line break is not desired one can use the backslash \ to break the line without inserting a line break. A line break in a string can also be inserted with the string \n. Here are some examples:

     "This string will be interpreted
     into two lines exactly as it is"
     
     "This string is specified with two lines \
     but interpreted as specified in only one line \
     i.e., without explicit line break"
     
     "This string\nwill have a line break"

Moreover, if the character " must be specified in the string, it will have to be escaped with the backslash15:

     "This string contains \"a quoted string\" inside"

The part that must be provided in the correct order is

     option <long> <short> "<desc>"

while the other specifications can be given in any order16. Thus, for instance

     option <long> <short> "<desc>" {argtype} {typestr="<type descr>"}

is the same as

     option <long> <short> "<desc>" {typestr="<type descr>"} {argtype}

Comments begin with # in any place (but in strings) of the line and ends in the end of line.

Notice that the options -h,--help and -V,--version are added automatically; however, if you specify an option yourself that has h as short form, then only --help is added17. The same holds for -V,--version.

In case hidden options are used, See Hidden options, the command line option --full-help will also be generated. This will print also the hidden options18.

If there's at least one option with details, the command line option --detailed-help will also be generated. This will print also the details for options and hidden options19.

Options can be part of sections, that provide a more meaningful descriptions of the options. A section can be defined with the following syntax (the sectiondesc is optional) and all the options following a section declaration are considered part of that sections:

     section "section name" {sectiondesc="optional section description"}

Notice that the separation in sections is stronger than separation in groups of mutual exclusive options (see Group options). Furthermore, sections should not be inserted among group options (but only externally). A section makes sense only if it is followed by some options. If you don't specify any option after a section, that section will not be printed at all. If you need to simply insert some text in the output of --help, then you must use text, explained in the next paragraph.

You can insert, among options, a textual string that will be printed in the output of --help20:

     text "\nA text description with possible line\nbreaks"

Of course, you can use this mechanism even to manually insert blank lines among options with an empty text string:

     text ""

You can also specify the list of values that can be passed to an option (if the type is not specified, the option has type string). More on this feature can be found in Options with enumerated values. If a value that is not in the list is passed, an error is raised. You can think of such options as enumerated options. It is not necessary to pass the complete value at the command line option: a non ambiguous prefix will do. For instance, if the accepted values are "foo","bar","foobar", then you can pass at the command line the value "b" and the value "bar" will be selected, or the value "foob" and the value "foobar" will be selected; instead, passing the value "fo" will raise an ambiguity error.

Here's an example of such a file (the file is called sample1.ggo)

     # Name of your program
     package "sample1" # don't use package if you're using automake
     # Version of your program
     version "2.0"   # don't use version if you're using automake
     
     # Options
     option  "str-opt"         s "A string option, for a filename"
             string typestr="filename"     optional
     text "\nA brief text description"
     text " before the other options.\n"
     option  "my-opt"          m "Another integer option, \
     this time the description of the option should be \"quite\" long to \
     require wrapping... possibly more than one wrapping :-) \
     especially if I\nrequire a line break"      int     optional
     option  "int-opt"         i "A int option"         int        yes
     section "more involved options"
             sectiondesc="the following options\nare more complex"
     text ""
     option  "flag-opt"        - "A flag option"        flag       off
     option  "funct-opt"       F "A function option"    optional
         details="\nA function option is basically an option with no argument.\
       It can be used, e.g., to specify a specific behavior for a program.
     
     Well, this further explanation is quite useless, but it's only to \
     show an example of an option with details, \
     which will be printed only when --detailed-help is given \
     at the command line."
     section "last option section"
     option  "long-opt"        - "A long option"        long       optional
     option  "def-opt"         - "A string option with default"
             string default="Hello" optional
     option  "enum-opt"         - "A string option with list of values"
             values="foo","bar","hello","bye" default="hello" optional
     option  "secret"         S "hidden option will not appear in --help"
             int optional hidden
     option  "dependant"         D
             "option that depends on str-opt" int optional dependon="str-opt"
     text "\nAn ending text."
     

The simplest way to use gengetopt is to pass this file as the standard input, i.e.:

     gengetopt < sample1.ggo

By default gengetopt generates cmdline.h and cmdline.c. Otherwise we can specify these names with a command line option:

     gengetopt < sample1.ggo --file-name=cmdline1 --unamed-opts

The option --unamed-opts allows the generated command line parser to accept also names, without an option (for instance you can pass a file name without an option in front of it, and also use wildcards, such as *.c, foo*.? and so on). These are also called parameters (see Terminology). You can specify an optional description for these additional names (default is FILES).

In cmdline1.h you'll find the generated C struct:

     /** @file cmdline1.h
      *  @brief The header file for the command line option parser
      *  generated by GNU Gengetopt version 2.22
      *  http://www.gnu.org/software/gengetopt.
      *  DO NOT modify this file, since it can be overwritten
      *  @author GNU Gengetopt by Lorenzo Bettini */
     
     #ifndef CMDLINE1_H
     #define CMDLINE1_H
     
     /* If we use autoconf.  */
     #ifdef HAVE_CONFIG_H
     #include "config.h"
     #endif
     
     #include <stdio.h> /* for FILE */
     
     #ifdef __cplusplus
     extern "C" {
     #endif /* __cplusplus */
     
     #ifndef CMDLINE_PARSER_PACKAGE
     /** @brief the program name */
     #define CMDLINE_PARSER_PACKAGE "sample1"
     #endif
     
     #ifndef CMDLINE_PARSER_VERSION
     /** @brief the program version */
     #define CMDLINE_PARSER_VERSION "2.0"
     #endif
     
     /** @brief Where the command line options are stored */
     struct gengetopt_args_info
     {
       const char *help_help; /**< @brief Print help and exit help description.  */
       const char *detailed_help_help; /**< @brief Print help, including all details and hidden options, and exit help description.  */
       const char *full_help_help; /**< @brief Print help, including hidden options, and exit help description.  */
       const char *version_help; /**< @brief Print version and exit help description.  */
       char * str_opt_arg;       /**< @brief A string option, for a filename.  */
       char * str_opt_orig;       /**< @brief A string option, for a filename original value given at command line.  */
       const char *str_opt_help; /**< @brief A string option, for a filename help description.  */
       int my_opt_arg;       /**< @brief Another integer option, this time the description of the option should be \"quite\" long to require wrapping... possibly more than one wrapping :-) especially if I\nrequire a line break.  */
       char * my_opt_orig;       /**< @brief Another integer option, this time the description of the option should be \"quite\" long to require wrapping... possibly more than one wrapping :-) especially if I\nrequire a line break original value given at command line.  */
       const char *my_opt_help; /**< @brief Another integer option, this time the description of the option should be \"quite\" long to require wrapping... possibly more than one wrapping :-) especially if I\nrequire a line break help description.  */
       int int_opt_arg;       /**< @brief A int option.  */
       char * int_opt_orig;       /**< @brief A int option original value given at command line.  */
       const char *int_opt_help; /**< @brief A int option help description.  */
       int flag_opt_flag;       /**< @brief A flag option (default=off).  */
       const char *flag_opt_help; /**< @brief A flag option help description.  */
       const char *funct_opt_help; /**< @brief A function option help description.  */
       long long_opt_arg;       /**< @brief A long option.  */
       char * long_opt_orig;       /**< @brief A long option original value given at command line.  */
       const char *long_opt_help; /**< @brief A long option help description.  */
       char * def_opt_arg;       /**< @brief A string option with default (default='Hello').  */
       char * def_opt_orig;       /**< @brief A string option with default original value given at command line.  */
       const char *def_opt_help; /**< @brief A string option with default help description.  */
       char * enum_opt_arg;       /**< @brief A string option with list of values (default='hello').  */
       char * enum_opt_orig;       /**< @brief A string option with list of values original value given at command line.  */
       const char *enum_opt_help; /**< @brief A string option with list of values help description.  */
       int secret_arg;       /**< @brief hidden option will not appear in --help.  */
       char * secret_orig;       /**< @brief hidden option will not appear in --help original value given at command line.  */
       const char *secret_help; /**< @brief hidden option will not appear in --help help description.  */
       int dependant_arg;       /**< @brief option that depends on str-opt.  */
       char * dependant_orig;       /**< @brief option that depends on str-opt original value given at command line.  */
       const char *dependant_help; /**< @brief option that depends on str-opt help description.  */
     
       unsigned int help_given ;       /**< @brief Whether help was given.  */
       unsigned int detailed_help_given ;       /**< @brief Whether detailed-help was given.  */
       unsigned int full_help_given ;       /**< @brief Whether full-help was given.  */
       unsigned int version_given ;       /**< @brief Whether version was given.  */
       unsigned int str_opt_given ;       /**< @brief Whether str-opt was given.  */
       unsigned int my_opt_given ;       /**< @brief Whether my-opt was given.  */
       unsigned int int_opt_given ;       /**< @brief Whether int-opt was given.  */
       unsigned int flag_opt_given ;       /**< @brief Whether flag-opt was given.  */
       unsigned int funct_opt_given ;       /**< @brief Whether funct-opt was given.  */
       unsigned int long_opt_given ;       /**< @brief Whether long-opt was given.  */
       unsigned int def_opt_given ;       /**< @brief Whether def-opt was given.  */
       unsigned int enum_opt_given ;       /**< @brief Whether enum-opt was given.  */
       unsigned int secret_given ;       /**< @brief Whether secret was given.  */
       unsigned int dependant_given ;       /**< @brief Whether dependant was given.  */
     
       char **inputs ; /**< @brief unamed options (options without names) */
       unsigned inputs_num ; /**< @brief unamed options number */
     } ;
     
     /** @brief The additional parameters to pass to parser functions */
     struct cmdline_parser_params
     {
       int override; /**< @brief whether to override possibly already present options (default 0) */
       int initialize; /**< @brief whether to initialize the option structure gengetopt_args_info (default 1) */
       int check_required; /**< @brief whether to check that all required options were provided (default 1) */
       int check_ambiguity; /**< @brief whether to check for options already specified in the option structure gengetopt_args_info (default 0) */
       int print_errors; /**< @brief whether getopt_long should print an error message for a bad option (default 1) */
     } ;
     
     /** @brief the purpose string of the program */
     extern const char *gengetopt_args_info_purpose;
     /** @brief the usage string of the program */
     extern const char *gengetopt_args_info_usage;
     /** @brief all the lines making the help output */
     extern const char *gengetopt_args_info_help[];
     /** @brief all the lines making the full help output (including hidden options) */
     extern const char *gengetopt_args_info_full_help[];
     /** @brief all the lines making the detailed help output (including hidden options and details) */
     extern const char *gengetopt_args_info_detailed_help[];
     
     /**
      * The command line parser
      * @param argc the number of command line options
      * @param argv the command line options
      * @param args_info the structure where option information will be stored
      * @return 0 if everything went fine, NON 0 if an error took place
      */
     int cmdline_parser (int argc, char * const *argv,
       struct gengetopt_args_info *args_info);
     
     /**
      * The command line parser (version with additional parameters - deprecated)
      * @param argc the number of command line options
      * @param argv the command line options
      * @param args_info the structure where option information will be stored
      * @param override whether to override possibly already present options
      * @param initialize whether to initialize the option structure my_args_info
      * @param check_required whether to check that all required options were provided
      * @return 0 if everything went fine, NON 0 if an error took place
      * @deprecated use cmdline_parser_ext() instead
      */
     int cmdline_parser2 (int argc, char * const *argv,
       struct gengetopt_args_info *args_info,
       int override, int initialize, int check_required);
     
     /**
      * The command line parser (version with additional parameters)
      * @param argc the number of command line options
      * @param argv the command line options
      * @param args_info the structure where option information will be stored
      * @param params additional parameters for the parser
      * @return 0 if everything went fine, NON 0 if an error took place
      */
     int cmdline_parser_ext (int argc, char * const *argv,
       struct gengetopt_args_info *args_info,
       struct cmdline_parser_params *params);
     
     /**
      * Save the contents of the option struct into an already open FILE stream.
      * @param outfile the stream where to dump options
      * @param args_info the option struct to dump
      * @return 0 if everything went fine, NON 0 if an error took place
      */
     int cmdline_parser_dump(FILE *outfile,
       struct gengetopt_args_info *args_info);
     
     /**
      * Save the contents of the option struct into a (text) file.
      * This file can be read by the config file parser (if generated by gengetopt)
      * @param filename the file where to save
      * @param args_info the option struct to save
      * @return 0 if everything went fine, NON 0 if an error took place
      */
     int cmdline_parser_file_save(const char *filename,
       struct gengetopt_args_info *args_info);
     
     /**
      * Print the help
      */
     void cmdline_parser_print_help(void);
     /**
      * Print the full help (including hidden options)
      */
     void cmdline_parser_print_full_help(void);
     /**
      * Print the detailed help (including hidden options and details)
      */
     void cmdline_parser_print_detailed_help(void);
     /**
      * Print the version
      */
     void cmdline_parser_print_version(void);
     
     /**
      * Initializes all the fields a cmdline_parser_params structure 
      * to their default values
      * @param params the structure to initialize
      */
     void cmdline_parser_params_init(struct cmdline_parser_params *params);
     
     /**
      * Allocates dynamically a cmdline_parser_params structure and initializes
      * all its fields to their default values
      * @return the created and initialized cmdline_parser_params structure
      */
     struct cmdline_parser_params *cmdline_parser_params_create(void);
     
     /**
      * Initializes the passed gengetopt_args_info structure's fields
      * (also set default values for options that have a default)
      * @param args_info the structure to initialize
      */
     void cmdline_parser_init (struct gengetopt_args_info *args_info);
     /**
      * Deallocates the string fields of the gengetopt_args_info structure
      * (but does not deallocate the structure itself)
      * @param args_info the structure to deallocate
      */
     void cmdline_parser_free (struct gengetopt_args_info *args_info);
     
     /**
      * Checks that all the required options were specified
      * @param args_info the structure to check
      * @param prog_name the name of the program that will be used to print
      *   possible errors
      * @return
      */
     int cmdline_parser_required (struct gengetopt_args_info *args_info,
       const char *prog_name);
     
     extern char *cmdline_parser_enum_opt_values[] ;       /**< @brief Possible values for enum-opt.  */
     
     
     #ifdef __cplusplus
     }
     #endif /* __cplusplus */
     #endif /* CMDLINE1_H */
     

The <option>_given field is set to 1 when an argument for <option> has been specified (otherwise it is 0)21. This fields also counts the times a multiple option is specified (see Multiple Options). If the option accepts an argument and it is not of flag type The <option>_arg field is set to the value passed at the command line. The <option>_arg field has the corresponding C type specified in the file passed to gengetopt.

Notice that if an option has a default value, then the corresponding <option>_arg will be initialized with that value but the corresponding <option>_given will NOT be initialized to 1. Thus, <option>_given will effectively inform you if the user has specified that command line option.

The additional field <option>_orig is always a string containing the original value passed at the command line. This may be different, for instance, in case of numerical arguments: gengetopt converts the passed value (a string) into the corresponding numerical type; due to conversions, float representations, etc., this may not correspond exactly to the original value passed at command line. It can also be different when enumerated options are used (see above): in particular the <option>_arg field will contain a value taken from the specified list, while <option>_orig contains the (non-ambiguous) prefix specified at the command line.

The user can always access this original value by using <option>_orig instead of <option>_arg, as he sees fit22. For instance, gengetopt itself uses the original value when it saves the command line options into a file (see the _file_save function in the following). However, apart from very specific command line processing, the user might hardly need the <option>_orig field, and can be always safely use <option>_arg.

The <option>_help contains the string (concerning this very option) that is printed when --help command line is given.

If it is of flag type, only the field <option>_flag is generated.

The strings cmdline_parser_purpose and cmdline_parser_usage contain the purpose as specified in the input file and the generated “usage” string as printed when --help command line is given. Finally, the string array cmdline_parser_help contains the strings (one for each option) printed when --help command line is given (this array is terminated by a null string element). If hidden options are used also the cmdline_parser_full_help array is available (containing also help strings concerning hidden options). If at least one option has details, then the cmdline_parser_detailed_help array is available (containing also help strings concerning hidden options and details for options). All these strings can be used by the programmer to build a customized help output23.

Even if <option>_given is 0, the corresponding <option>_arg is set to default value (if one has been specified for <option>). However, in this case, the <option>_orig is set to NULL.

Notice that by default the generated function is called cmdline_parser (see the command line options below, to override this name), and it takes the arguments that main receives and a pointer to such a struct, that it will be filled. Another version, cmdline_parser2, can be specified more arguments. Since you typically need this second version only in conjunction with other “kinds” of parsers such as configuration files and multiple parsers, you can find more details about it in Configuration files.

IMPORTANT: The array passed to the parser function (that in turn is passed to getopt_long is expected to have in the first element (of index 0) the name of the program that was invoked. This will be used, for instance, for printing possible errors.

cmdline_parser_free can be called to deallocate memory allocated by the parser for string and multiple options.

cmdline_parser_init can be called to initialize the struct (it is not mandatory, since it is done automatically by the command line parser).

cmdline_parser_file_save24 can be used to save the command line options into a file. The contents of this file are consistent with the configuration files (Configuration files). Notice that if an option has a default value, this option will be saved into the file only if it was passed explicitly at command line (or read from a configuration file), i.e., default values will not be saved into the file. Alternatively, you can use cmdline_parser_dump25 that takes as the first parameter an already open stream (FILE *) instead of a file name.

And here's how these functions can be used inside the main program:

     /* main1.cc */
     /* we try to use gengetopt generated file in a C++ program */
     /* we don't use autoconf and automake vars */
     
     #include <iostream>
     #include "stdlib.h"
     
     #include "cmdline1.h"
     
     using std::cout;
     using std::endl;
     
     int
     main (int argc, char **argv)
     {
       gengetopt_args_info args_info;
     
       cout << "This one is from a C++ program" << endl ;
       cout << "Try to launch me with some options" << endl ;
       cout << "(type sample1 --help for the complete list)" << endl ;
       cout << "For example: ./sample1 *.* --funct-opt" << endl ;
     
       /* let's call our cmdline parser */
       if (cmdline_parser (argc, argv, &args_info) != 0)
         exit(1) ;
     
       cout << "Here are the options you passed..." << endl;
     
       for ( unsigned i = 0 ; i < args_info.inputs_num ; ++i )
         cout << "file: " << args_info.inputs[i] << endl ;
     
       if ( args_info.funct_opt_given )
         cout << "You chose --funct-opt or -F." << endl ;
     
       if ( args_info.str_opt_given )
         cout << "You inserted " << args_info.str_opt_arg << " for " <<
           "--str-opt option." << endl ;
     
       if ( args_info.int_opt_given )
         cout << "This is the integer you input: " <<
           args_info.int_opt_arg << "." << endl;
     
       if (args_info.flag_opt_given)
         cout << "The flag option was given!" << endl;
     
       cout << "The flag is " << ( args_info.flag_opt_flag ? "on" : "off" ) <<
         "." << endl ;
     
       if (args_info.enum_opt_given) {
         cout << "enum-opt value: " << args_info.enum_opt_arg << endl;
         cout << "enum-opt (original specified) value: "
             << args_info.enum_opt_orig << endl;
       }
     
       if (args_info.secret_given)
         cout << "Secret option was specified: " << args_info.secret_arg
             << endl;
     
       cout << args_info.def_opt_arg << "! ";
     
       cout << "Have a nice day! :-)" << endl ;
     
       cmdline_parser_free (&args_info); /* release allocated memory */
     
       return 0;
     }
     

Now you can compile main1.cc and the cmdline1.c generated by gengetopt and link all together to obtain sample1 executable:

     gcc -c cmdline1.c
     g++ -c main1.cc
     g++ -o sample1 cmdline1.o main1.o

(Here we assume that getopt_long is included in the standard C library; see Installation and No getopt_long).

Now let's try some tests with this program:

     $ ./sample1 -s "hello" --int-opt 1234
     This one is from a C++ program
     Try to launch me with some options
     (type sample1 --help for the complete list)
     For example: ./sample1 *.* --funct-opt
     Here are the options you passed...
     You inserted hello for --str-opt option.
     This is the integer you input: 1234.
     The flag is off.
     Have a nice day! :-)

You can also pass many file names to the command line (this also shows how flags work):

     $ ./sample1 *.h -i -100 -x
     This one is from a C++ program
     Try to launch me with some options
     (type sample1 --help for the complete list)
     For example: ./sample1 *.* --funct-opt
     Here are the options you passed...
     file: cmdline1.h
     file: cmdline2.h
     file: cmdline.h
     file: getopt.h
     This is the integer you input: -100.
     The flag is on.
     Have a nice day! :-)

And if we try to omit the --int-opt (or -i), which is required, we get an error:

     $ ./sample1
     This one is from a C++ program
     Try to launch me with some options
     (type sample1 --help for the complete list)
     For example: ./sample1 *.* --funct-opt
     sample1: `--int-opt' (`-i') option required!

Now, let's test the enumerated options, notice the use of a prefix for specifying an acceptable value, and the difference between the actual passed value and the one recorded in <option>_arg:

     $ ./sample1 -i 10 --enum-opt h
     ...
     enum-opt value: hello
     enum-opt (original specified) value: h
     ...

While the next one raises an ambiguity error (between "bar" and "bye"):

     $ ./sample1 -i 10 --enum-opt b
     ...
     ./sample1: ambiguous argument, "b", for option `--enum-opt'

Here is the output of --help of the parser generated from sample1.ggo by specifying the following options to gengetopt: --long-help -u --show-required (see Invoking gengetopt for further explanation for these command line options).

     This one is from a C++ program
     Try to launch me with some options
     (type sample1 --help for the complete list)
     For example: ./sample1 *.* --funct-opt
     sample1 2.0
     
     Usage: sample1 -iINT|--int-opt=INT [-h|--help] [--detailed-help] [--full-help]
              [-V|--version] [-sfilename|--str-opt=filename] [-mINT|--my-opt=INT]
              [--flag-opt] [-F|--funct-opt] [--long-opt=LONG] [--def-opt=STRING]
              [--enum-opt=STRING] [-DINT|--dependant=INT] [FILES]...
     
       -h, --help              Print help and exit
           --detailed-help     Print help, including all details and hidden options,
                                 and exit
           --full-help         Print help, including hidden options, and exit
       -V, --version           Print version and exit
       -s, --str-opt=filename  A string option, for a filename
     
     A brief text description before the other options.
     
       -m, --my-opt=INT        Another integer option, this time the description of
                                 the option should be "quite" long to require
                                 wrapping... possibly more than one wrapping :-)
                                 especially if I
                                 require a line break
       -i, --int-opt=INT       A int option (mandatory)
     
     more involved options:
       the following options
       are more complex
     
           --flag-opt          A flag option  (default=off)
       -F, --funct-opt         A function option
     
     last option section:
           --long-opt=LONG     A long option
           --def-opt=STRING    A string option with default  (default=`Hello')
           --enum-opt=STRING   A string option with list of values  (possible
                                 values="foo", "bar", "hello", "bye"
                                 default=`hello')
       -D, --dependant=INT     option that depends on str-opt
     
     An ending text.

Notice how filename is printed instead of STRING for the option --str-opt (since typestr was used in the sample1.ggo file) and how the description of --my-opt is wrapped to 80 columns, and how the \n is actually interpreted as a newline request. Also the usage string is wrapped. Moreover, since -S,--secret is an hidden option (See Hidden options.) it is not printed; if you wanted that to be printed, you should use --full-help. The option --func-opt has also the details, but they are not printed with --help.

Finally, notice how the text strings are printed in the help output (and the empty line after the “more involved options” section achieved with an empty text string).

Instead, here is the output of --detailed-help of the parser generated from sample1.ggo. You may want to compare this output with the one produced by --help (See Output of --help.); in particular, you may notice that the hidden option --secret is actually printed and the details of --func-opt are printed too:

     This one is from a C++ program
     Try to launch me with some options
     (type sample1 --help for the complete list)
     For example: ./sample1 *.* --funct-opt
     sample1 2.0
     
     Usage: sample1 -iINT|--int-opt=INT [-h|--help] [--detailed-help] [--full-help]
              [-V|--version] [-sfilename|--str-opt=filename] [-mINT|--my-opt=INT]
              [--flag-opt] [-F|--funct-opt] [--long-opt=LONG] [--def-opt=STRING]
              [--enum-opt=STRING] [-DINT|--dependant=INT] [FILES]...
     
       -h, --help              Print help and exit
           --detailed-help     Print help, including all details and hidden options,
                                 and exit
           --full-help         Print help, including hidden options, and exit
       -V, --version           Print version and exit
       -s, --str-opt=filename  A string option, for a filename
     
     A brief text description before the other options.
     
       -m, --my-opt=INT        Another integer option, this time the description of
                                 the option should be "quite" long to require
                                 wrapping... possibly more than one wrapping :-)
                                 especially if I
                                 require a line break
       -i, --int-opt=INT       A int option (mandatory)
     
     more involved options:
       the following options
       are more complex
     
           --flag-opt          A flag option  (default=off)
       -F, --funct-opt         A function option
     
       A function option is basically an option with no argument.  It can be used,
       e.g., to specify a specific behavior for a program.
     
       Well, this further explanation is quite useless, but it's only to show an
       example of an option with details, which will be printed only when
       --detailed-help is given at the command line.
     
     last option section:
           --long-opt=LONG     A long option
           --def-opt=STRING    A string option with default  (default=`Hello')
           --enum-opt=STRING   A string option with list of values  (possible
                                 values="foo", "bar", "hello", "bye"
                                 default=`hello')
       -S, --secret=INT        hidden option will not appear in --help
       -D, --dependant=INT     option that depends on str-opt
     
     An ending text.

If you're curious you may want to take a look at the generated C file cmdline1.c.

You may find other examples in /prefix/share/doc/gengetopt/examples or in the tests of the source tarbal.


Next: , Previous: Basic Usage, Up: Top