Gengetopt is a tool to write option parsing code for C programs.
This is Edition 2.16 of the Gengetopt manual.
It documents GNU Gengetopt version 2.16.
Gengetopt is a tool to generate C code to parse the command line
arguments argc
and argv
that are part of every C or C++
program. The generated code uses the C library function
getopt_long
to perform the actual command line parsing.
This manual is written for C and C++ programmers, specifically the lazy ones. If you've written any non-trivial C program, you've had to deal with argument parsing. It isn't particularly difficult, nor is it particularly exciting. It is one of the classic programming nuisances, which is why most books on programming leave it as an exercise for the reader. Gengetopt can save you from this work, leaving you free to focus on the interesting parts of your program.
Thus your program will be able to handle command line options such as:
myprog --input foo.c -o foo.o --no-tabs -i 100 *.class
And both long options (those that start with --
) and short
options (start with -
and consist of only one character) can be
handled (see Terminology for further details). For standards about
short and long options you may want to take a look at the GNU Coding
Standards (http://www.gnu.org/prep/standards_toc.html).
Gengetopt can also generate a function to save the command line options into a file (see Basic Usage), and a function to read the command line options from a file (see Configuration files). Of course, these two kinds of files are compliant.
Gengetopt is free software; you are free to use, share and modify it under the terms of the GNU General Public License that accompanies this manual.
The code that Gengetopt generates is also free software; however it is licensed with a simple all-permissive license instead of the GPL or LGPL. You are free to do anything you like with the generated code, including incorporating it into or linking it with proprietary software.
Gengetopt was originally written by Roberto Arturo Tena Sanchez. It is currently maintained by Lorenzo Bettini http://www.lorenzobettini.it.
A primordial version of Terminology was written by Adam Greenblatt.
See the file INSTALL for detailed building and installation instructions; anyway if you're used to compiling Linux software that comes with sources you may simply follow the usual procedure, i.e. untar the file you downloaded in a directory and then:
cd <source code main directory> ./configure make make install
Note: unless you specify a different install directory by
--prefix
option of
configure (e.g. ./configure --prefix=<your home>
),
you must be root to run make install
.
Files will be installed in the following directories:
executables
/prefix/bin
docs
/prefix/share/doc/gengetopt
examples
/prefix/share/doc/gengetopt/examples
additional files
/prefix/share/gengetopt
Default value for prefix is /usr/local
but you may change it with --prefix
option to configure.
You can download it from GNU's ftp site: ftp://ftp.gnu.org/gnu/gengetopt or from one of its mirrors (see http://www.gnu.org/prep/ftp.html).
I do not distribute Windows binaries anymore; since, they can be easily built by using Cygnus C/C++ compiler, available at http://www.cygwin.com. However, if you don't feel like downloading such compiler, you can request such binaries directly to me, by e-mail (find my e-mail at my home page) and I can send them to you.
Archives are digitally signed by me (Lorenzo Bettini) with GNU gpg (http://www.gnupg.org). My GPG public key can be found at my home page (http://www.lorenzobettini.it).
You can also get the patches, if they are available for a particular release (see below for patching from a previous version).
This project's CVS repository can be checked out through anonymous (pserver) CVS with the following instruction:
cvs -z3 -d:pserver:anonymous@cvs.savannah.gnu.org:/sources/gengetopt co gengetopt
Further instructions can be found at the address:
http://savannah.gnu.org/projects/gengetopt.
Please notice that this way you will get the latest development sources of Gengetopt, which may also be unstable. This solution is the best if you intend to correct/extend this program: you should send me patches against the latest cvs repository sources.
If, on the contrary, you want to get the sources of a given release,
through cvs, say, e.g., version X.Y.Z, you must specify the tag
rel_X_Y_Z
when you run the cvs command or the cvs update
command.
When you compile the sources that you get through the cvs repository,
before running the configure
and make
commands, you
should, at least the first time, run the command:
sh reconf
This will run the autotools commands in the correct order, and also copy
possibly missing files. You should have installed recent versions of
automake
and autoconf
in order for this to succeed.
You will also need flex
and bison
.
NOTICE: This convention holds since release 2.14.
Gengetopt has been developed under GNU/Linux, using gcc (C++), and bison (yacc) and flex (lex), and ported under Win32 with Cygnus C/C++compiler, available at http://www.cygwin.com. I used the excellent GNU Autoconf and GNU Automake. I also used Autotools (ftp://ftp.ugcs.caltech.edu/pub/elef/autotools) which creates a starting source tree (according to GNU standards) with autoconf, automake starting files.
Moreover Gengen (http://www.lorenzobettini.it/software/gengen) is used for automatically generating the code that generates the command line parser.
Actually, you don't need all these tools above to build source-highlight because I provide generated sources, unless you want to develop source-highlight.
The code generated by gengetopt relies on the getopt_long
function that is usually in the standard C library; however, there may
be some implementations of the C library that don't include it; in this
case you have to link the program that uses the file generated by
gengetopt with the files getopt.c and getopt1.c and
include gnugetopt.h in your project. We obviously provide these
files in the utility files directory (<install
prefix>/share/gengetopt). These files are part of the GNU C library.
You may want to take a look at getopt_long
man page.
Read also No getopt_long, for instructions on how to check whether getopt_long is part of the library and how to deal with their lacking (using autoconf and automake).
If you downloaded a patch, say gengetopt-1.3-1.3.1-patch.gz (i.e., the patch to go from version 1.3 to version 1.3.1), cd to the directory with sources from the previous version (gengetopt-1.3) and type:
gunzip -cd ../gengetopt-1.3-1.3.1.patch.gz | patch -p1
and restart the compilation process (if you had already run configure a simple make should do).
The command line options, which have to be handled by gengetopt generated function, are specified in a file (typically with .ggo extension). This file consist in lines of sentences with the following formats, commands in {} are optional1:
package <packname> version <version> option <long> <short> <desc> \ {argtype} {typestr="<type descr>"} \ {values="<value1>","<value2>",...} \ {default="<default value>"} \ {dependon="<other option>"} \ {required} {argoptional} {multiple} \ {hidden} option <long> <short> <desc> flag <on/off>
Where:
package
PACKAGE
generated by autoconf.
version
VERSION
generated by autoconf.
purpose
long
-
) 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
-
is specified, then no short option is considered for the long
option (thus long options with no associated short options are allowed).
desc
-
) and a dot (.
). The first character must not be
a space. This description will be printed during the output of
--help
. Wrapping will be automatically performed, and \n
is interpreted as a newline request.
argtype
string
, int
, short
, long
, float
,
double
, longdouble
or longlong
. If no type is
specified the option does not accept an argument.
typestr
--help
(e.g., "filename"
instead
of simply STRING
, or "portnumber"
instead of simply
INT
).
values
default
dependon
required
yes
or no
. This specifies whether such option must be
given at each program invocation.
argoptional
=
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
.
multiple
hidden
--help
but it can still be specified at
command line2. In case hidden options
are used, the command line option --full-help
will also be
generated. This will print also the hidden options3.
on/off
on
or off
. This is the state of the flag when the program
starts. If user specifies the option, the flag toggles.
The part that must be provided in the correct order is
option <long> <short> <desc>
while the other specifications can be given in any order4. Thus, for instance
option <long> <short> <desc> {argtype} {typestr="<type descr>"}
is the same as
option <long> <short> <desc> {typestr="<type descr>"} {argtype}
Comments begins with #
in any place 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 or help
as long form, then
-h,--help
is not added (and you have to handle the help option
manually). 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 options5.
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"}
You can also specify the list of values
that can be passed to an
option (in that case the option has type string
). 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)
# file sample1.ggo option "str-opt" s "A string option, for a filename" \ string typestr="filename" no 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 no option "int-opt" i "A int option" int yes section "more involved options" \ sectiondesc="the following options\nare more complex" option "flag-opt" - "A flag option" flag off option "funct-opt" F "A function option" no section "last option section" option "long-opt" - "A long option" long no option "def-opt" - "A string option with default" \ string default="Hello" no option "enum-opt" - "A string option with list of values" \ values="foo","bar","hello","bye" default="hello" no option "secret" S "hidden option will not appear in --help" \ int no hidden option "dependant" D "option that depends on str-opt" \ int no dependon="str-opt"
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:
/* cmdline1.h */ /* File autogenerated by gengetopt version 2.16 */ #ifndef CMDLINE1_H #define CMDLINE1_H /* If we use autoconf. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #ifdef __cplusplus extern "C" { #endif /* __cplusplus */ #ifndef CMDLINE_PARSER_PACKAGE #define CMDLINE_PARSER_PACKAGE "sample1" #endif #ifndef CMDLINE_PARSER_VERSION #define CMDLINE_PARSER_VERSION "2.0" #endif struct gengetopt_args_info { char * str_opt_arg; /* A string option, for a filename. */ char * str_opt_orig; /* A string option, for a filename original value given at command line. */ int my_opt_arg; /* 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; /* 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. */ int int_opt_arg; /* A int option. */ char * int_opt_orig; /* A int option original value given at command line. */ int flag_opt_flag; /* A flag option (default=off). */ long long_opt_arg; /* A long option. */ char * long_opt_orig; /* A long option original value given at command line. */ char * def_opt_arg; /* A string option with default (default='Hello'). */ char * def_opt_orig; /* A string option with default original value given at command line. */ char * enum_opt_arg; /* A string option with list of values (default='hello'). */ char * enum_opt_orig; /* A string option with list of values original value given at command line. */ int secret_arg; /* hidden option will not appear in --help. */ char * secret_orig; /* hidden option will not appear in --help original value given at command line. */ int dependant_arg; /* option that depends on str-opt. */ char * dependant_orig; /* option that depends on str-opt original value given at command line. */ int help_given ; /* Whether help was given. */ int full_help_given ; /* Whether full-help was given. */ int version_given ; /* Whether version was given. */ int str_opt_given ; /* Whether str-opt was given. */ int my_opt_given ; /* Whether my-opt was given. */ int int_opt_given ; /* Whether int-opt was given. */ int flag_opt_given ; /* Whether flag-opt was given. */ int funct_opt_given ; /* Whether funct-opt was given. */ int long_opt_given ; /* Whether long-opt was given. */ int def_opt_given ; /* Whether def-opt was given. */ int enum_opt_given ; /* Whether enum-opt was given. */ int secret_given ; /* Whether secret was given. */ int dependant_given ; /* Whether dependant was given. */ char **inputs ; /* unamed options */ unsigned inputs_num ; /* unamed options number */ } ; int cmdline_parser (int argc, char * const *argv, struct gengetopt_args_info *args_info); int cmdline_parser2 (int argc, char * const *argv, struct gengetopt_args_info *args_info, int override, int initialize, int check_required); int cmdline_parser_file_save(const char *filename, struct gengetopt_args_info *args_info); void cmdline_parser_print_help(void); void cmdline_parser_print_full_help(void); void cmdline_parser_print_version(void); void cmdline_parser_init (struct gengetopt_args_info *args_info); void cmdline_parser_free (struct gengetopt_args_info *args_info); int cmdline_parser_required (struct gengetopt_args_info *args_info, const char *prog_name); extern char *cmdline_parser_enum_opt_values[] ; /* Possible values for enum-opt. */ #ifdef __cplusplus } #endif /* __cplusplus */ #endif /* CMDLINE1_H */
The <option>_given
field is set to a value different from 0 when
an argument for <option>
has been specified. 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. 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 convertions, 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
fit6. For instance, gengetopt itselfs 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
.
If it is of flag
type, only the field <option>_flag
is generated.
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.
cmdline_parser_free
can be called to deallocate memory allocated by the
parser for string and multiple options.
Notice that after calling this function, the parsing functions should not be called anymore.
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_save
7 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.
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 h ... ./sample1: ambiguous argument, "b", for option `--enum-opt'
Here is the output of --help
:
sample1 2.0 Usage: sample1 -iINT|--int-opt=INT [-h|--help] [-V|--version] -sfilename|--str-opt=filename -mINT|--my-opt=INT [--flag-opt] [-F|--funct-opt] --long-opt=LONG --def-opt=STRING [FILES]... -h, --help Print help 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 -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 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
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. 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
.
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.
This is the output of gengetopt --help
:
gengetopt This program generates a C function that uses getopt_long function to parse the command line options, validate them and fill a struct. Usage: gengetopt [OPTIONS]... -h, --help Print help and exit -V, --version Print version and exit -i, --input=filename input file (default std input) -f, --func-name=name name of generated function (default=`cmdline_parser') -a, --arg-struct-name=name name of generated args info struct (default=`gengetopt_args_info') -F, --file-name=name name of generated file (default=`cmdline') -c, --c-extension=ext extension of c file (default=`c') -H, --header-extension=ext extension of header file (default=`h') -l, --long-help long usage line in help -u, --unamed-opts[=STRING] accept options without names (e.g., file names) (default=`FILES') -n, --no-handle-help do not handle --help|-h automatically -N, --no-handle-version do not handle --version|-V automatically -e, --no-handle-error do not exit on errors -g, --gen-version put gengetopt version in the generated file (default=on) -C, --conf-parser generate a config file parser --set-package=STRING set the package name (override package defined in the .ggo file) --set-version=STRING set the version number (override version defined in the .ggo file) --show-help show the output of --help instead of generating code --show-full-help show the output of --help (including hidden options) instead of generating code --show-version show the output of --version instead of generating code
The options should be clear; in particular:
--func-name
--func-name
is given, cmdline_parser
is taken by default;
--arg-struct-name
gengetopt_args_info
)
--long-help
--unamed-opts
sample1 *.h
). You can
specify an optional description for these additional names (default is
FILES
).
--no-handle-help
--no-handle-version
--no-handle-help
(--no-handle-version
) is given the
command line option --help|-h
(--version|-V
) is not
handled automatically, so the programmer will be able to print some
other information; then the function for printing the standard help
(version) response can be used; this function is called
<parser-name>_print_help
(<parser-name>_print_version
),
where <parser-name>
is the name specified with --func-name
or the default, cmdline_parser
.
--no-handle-error
--no-handle-error
is given, an error in the parsing does not
provoke the exit of the program; instead, since the parser function, in
case of an error, returns a value different 0, the program can print a
help message, as gengetopt itself does in case of an error (try it!).
--gen-version
--show-help
--show-full-help
--show-version
--help
,
--full-help
and --version
command lines without
generating any code, See Automatically added options.
For instance, I use the --show-help
option to generate a
texinfo file with the output of help (this also shows an example of
use of --set-package
and --set-version
):
../src/gengetopt --show-help -i ../src/cmdline.ggo \ --set-package="gengetopt" \ --set-version="" > help_output.texinfo
You may have already guessed it: gengetopt uses gengetopt itself for
command line options, and its specification file is cmdline.ggo
in the source directory. In particular the command line for gengetopt
itself is generated with the following command:
gengetopt --input=cmdline.ggo --no-handle-version \ --no-handle-help --no-handle-error
Indeed when --help|-h
is passed on the command line, gengetopt will call
cmdline_parser_print_help()
and then the lines for reporting bugs. When
--version|-V
is passed, it will call cmdline_parser_print_version() and
then prints a copyright. If an error occurs it prints a message on the
screen:
$ ./gengetopt --zzzz ./gengetopt: unrecognized option `--zzzz' Run gengetopt --help to see the list of options.
An argument is an element of the argv
array passed into
your C or C++ program by your operating system.
An option is an argument that begins with -, or --.
A value is an argument, or part of an argument, that is associated with a particular option (an option may also not accept any value). For example, in
> ls --width=80
ls is called with one argument, --width=80,
which is an option that has a value, 80
, while in
> ls --width 80
ls is called with two arguments, --width,
which is an option, and 80
which might or might not be a value.
In this case, whether the 80
is treated as a value associated
with the preceding --width option, or as the name of a file to
list depends on how ls parses the --width option.
The order in which options are specified is usually unimportant:
> ls -a -l > ls -l -a
both do exactly the same thing.
An parameter is an argument that is not an option. For example, in
> cp --archive source dest
cp is called with three arguments, the option
--archive, the parameter source
, and the parameter
dest
. Unlike options, the order in which parameters are
specified usually is important:
> cp --archive --verbose source dest > cp --verbose --archive source dest > cp --archive source --verbose dest > cp --archive --verbose dest source
The first three cp commands do the same thing, but the fourth one is completely different.
If you're new to Gengetopt, you may wish to skip the rest of this section. It goes into more detail about different sorts of options, and how they are parsed.
Note that some parameters may begin with - or --. Equivalently, not all arguments that begin with - or -- are options. Consider
> ls -- -file > tar -c -f - . > ../foo.tar
The ls command has two arguments; the first
argument, -- is ignored by ls, but causes the
-file argument to be interpreted as a parameter. The tar
command has four arguments. The -c argument tells tar to
create an archive; the -f argument, which takes a value,
-
, tells tar that the archive should be written onto the standard
output, and the fourth argument, .
, tells tar what directories to
include in the archive. (The remaining two items, >
and
../foo.tar
, tell the shell to redirect the tar
command's output to the file ../foo.tar. The tar command
doesn't even see them.)
The GNU convention is that - by itself is always interpreted as a value or parameter, while the first -- by itself is always ignored, but causes all subsequent arguments to be interpreted as parameters. Gengetopt always behaves this way.
A short option is an option that begins with -. Not including the leading dash, short options must be one character long:
> ls -a -l -t --width=80
The -a, -l, and -t options are all short options. Multiple short options may be combined into a single argument:
> ls -alt --width=80
is equivalent to the above example.
A long option is an option that begins with - or --. Ignoring the leading punctuation, long options may be one or more characters long:
> ls --all -fs
The ls command has two arguments; the long option --all, and the pair of short options -fs.
Long options need not have synonymous short options; after all, complex programs like cc have more long options than there are valid short option characters; it wouldn't be possible to assign a short option to each of them. Short options are encouraged, but not required, to have a synonymous long option.
Long options may be abbreviated, as long as the abbreviation is not ambiguous. Gengetopt automatically treats unambiguous abbreviations as synonyms.
Short options may have values just like long options, but if several short options are grouped together into one argument, only the last one may have a value. Values in the same argument as a long option are delimited by an equals sign, values in the same argument as a short option are not:
> ls --width 60 # ok, value is "60" > ls --width=60 # ok, value is "60" > ls -w60 # ok, value is "60" > ls -w 60 # ok, value is "60" > ls -w=60 # unexpected, value is "=60" > ls -T7 -w60 # ok, value for -T is 7, value for -w is 60 > ls -T7w60 # unexpected, value for -T is "7w60", no -w at all
A required option must be present, otherwise an error will be raised.
A multiple option is an option that may appear more than once on the command line. Gengetopt would create a tidy array for multiple options (see Multiple Options, for further details about dealing with multiple options).
It is also possible to group options; options belonging to a group are
considered in mutual exclusion. In order to use this feature, first the
group
has to be defined, and then a groupoption
can be defined. A
groupoption has basically the same syntax of a standard option, apart
that the required flag must not be specified (it would not make sense,
since the options of the same group are mutual exclusive) and the group
to which the option belongs has to be specified.
defgroup "<group name>" {groupdesc="<group description>"} {yes} groupoption <long> <short> <desc> <argtype> group="<group name>" \ {argoptional} {multiple}
If a group is defined as required, then one (but only one) option belonging to the group has to be specified.
Here's an example (taken from the test test_group_cmd.ggo):
defgroup "my grp2" defgroup "grp1" groupdesc="an option of this group is required" yes groupoption "opta" a "string a" group="grp1" multiple groupoption "optA" A "string A" string group="grp1" argoptional groupoption "optAmul" M "string M" string group="grp1" argoptional multiple groupoption "optb" b "string b" group="grp1" groupoption "optc" - "string c" group="my grp2" groupoption "optd" d "string d" group="my grp2"
The group grp1
is required, so either --opta
or
--optb
has to be specified (but only one of them). Here's the
output of some executions:
$ ./test_groups test_groups: 0 options of group grp1 were given. One is required $ ./test_groups -a OK $ ./test_groups -a -a OK (the same option given twice) $ ./test_groups -a -b test_groups: 2 options of group grp1 were given. One is required $ ./test_groups -a -c OK $ ./test_groups -a --optc -d test_groups: 2 options of group my grp2 were given. At most one is required
It is often useful to specify command line options directly in a
configuration file, so that the value of some options are read from this
file if they are not given as command line options. When the command
line option --conf-parser
is given to gengetopt, apart from the standard
command line option parser, also this additional parser is generated
(its name is <commandline_parser>_configfile
):
int <cmd_parser_name>_configfile (char * const filename, struct gengetopt_args_info *args_info, int override, int initialize, int check_required);
The parameter override
tells whether the values read in the
configuration file have to override those specified at the command line.
The initialize
tells whether the args_info struct has to be
initialize.
IMPORTANT: you have to explicitly set initialize
to true (i.e.,
different from 0) if you call the config file parser before the standard
command line option parser, otherwise unpredictable results may show.
The check_required
tells whether the check for required options
must be performed or not.
If you call the config file parser before the standard command line option parser and then you want to call the standard command line parser you MUST use this second version, passing 0 for initialized, so that collected values from the config file are not lost:
int <cmd_parser_name>2 (int argc, char * const *argv, struct gengetopt_args_info *args_info, int override, int initialize, int check_required);
Notice, that with this version you can also specify whether the options
passed at the command line must override the ones read from the config
file. If you set override
to 0, and a command line option is
given that has already been read from the config file, an error will be
raised. Moreover, you have to specify whether the check for missing
required options must be performed or not. This concerns also options
of a required group (Group options).
If you decide not to request the check for required option, you can test it manually, after the command line parsing returns by using the following generated function:
int <cmd_parser_name>_required (struct gengetopt_args_info *args_info, const char *program_name);
where program_name
is the name of your executable (usually you
should pass argv[0]
as argument). If the function returns a
value different from 0, then some required options are missing. An
error has already been printed by this function. This concerns also
options of a required group (Group options).
The config file has the following simple syntax: lines starting with # are considered comments and:
<option_name> = {<option_val>}
or simply (if the option does not take an argument):
<option_name>
which means that option_name
is given, and if it accepts an argument,
then its value is option_val
. The =
is not mandatory.
For instance here's a program that uses this feature (this is the test test_conf_parser):
/* test_conf_parser.c test */ /* test all kinds of options and the conf file parser */ #include <stdlib.h> #include <stdio.h> #include "test_conf_parser_cmd.h" static struct my_args_info args_info; int main (int argc, char **argv) { int i; int result = 0; if (test_conf_parser_cmd_parser (argc, argv, &args_info) != 0) { result = 1; goto stop; } /* override cmd options, but do not initialize args_info, check for required options */ if (test_conf_parser_cmd_parser_configfile (args_info.conf_file_arg, &args_info, 1, 0, 1) != 0) { result = 1; goto stop; } printf ("value of required: %s\n", args_info.required_arg); printf ("value of string: %s\n", args_info.string_arg); printf ("value of no-short_given: %d\n", args_info.no_short_given); printf ("value of int: %d\n", args_info.int_arg); printf ("value of float: %f\n", args_info.float_arg); printf ("value of multi-string_given: %d\n", args_info.multi_string_given); for (i = 0; i < args_info.multi_string_given; ++i) printf (" value of multi-string: %s\n", args_info.multi_string_arg [i]); printf ("value of multi-string-def_given: %d\n", args_info.multi_string_def_given); for (i = 0; i < args_info.multi_string_def_given; ++i) printf (" value of multi-string-def: %s\n", args_info.multi_string_def_arg [i]); if (!args_info.multi_string_def_given && args_info.multi_string_def_arg [0]) printf ("default value of multi-string-def: %s\n", args_info.multi_string_def_arg [0]); printf ("value of opta: %s\n", args_info.opta_arg); printf ("noarg given %d times\n", args_info.noarg_given); printf ("noarg_noshort given %d times\n", args_info.noarg_noshort_given); printf ("opt-arg given: %d\n", args_info.opt_arg_given); printf ("opt-arg value: %s\n", (args_info.opt_arg_arg ? args_info.opt_arg_arg : "not given")); if (args_info.file_save_given) { if (test_conf_parser_cmd_parser_file_save (args_info.file_save_arg, &args_info) == EXIT_FAILURE) result = 1; else printf ("saved configuration file %s\n", args_info.file_save_arg); } stop: test_conf_parser_cmd_parser_free (&args_info); return result; }
So if we use the following config file
# required option required "this is a test" float 3.14 no-short string another
and we run test_conf_parser
like that, we will have
./test_conf_parser -r bar -i 100 --float 2.14 --conf-file test_conf.conf value of required: this is a test value of string: another value of no-short: 1 value of int: 100 value of float: 3.140000
If, instead we call the test_conf_parser_cmd_parser_configfile
with 0
for override argument, we get the following result
value of required: bar value of string: another value of no-short: 1 value of int: 100 value of float: 2.140000
This second example use the second version of the command line parser: first call the configuration file parser and then the command line parser (the command line options will override the configuration file options):
/* test_conf_parser_ov2.c test */ /* test all kinds of options and the conf file parser */ /* differently from test_conf_parser_ov.c, first scan the conf file and then the command line */ #include <stdlib.h> #include <stdio.h> #include "test_conf_parser_cmd.h" static struct my_args_info args_info; int main (int argc, char **argv) { /* do not override command line options, initialize args_info */ if (test_conf_parser_cmd_parser_configfile ("./test_conf2.conf", &args_info, 0, 1, 0) != 0) exit(1); if (test_conf_parser_cmd_parser2 (argc, argv, &args_info, 1, 0, 1) != 0) exit(1) ; printf ("value of required: %s\n", args_info.required_arg); printf ("value of string: %s\n", args_info.string_arg); printf ("value of no-short_given: %d\n", args_info.no_short_given); printf ("value of int: %d\n", args_info.int_arg); printf ("value of float: %f\n", args_info.float_arg); test_conf_parser_cmd_parser_free (&args_info); return 0; }
This is an invocation and its results:
./test_conf_parser_ov2 -r "bar" --float 2.14 -i 100 value of required: bar value of string: another value of no-short: 1 value of int: 100 value of float: 2.140000
The generated config file parser function uses the constant
CONFIG_FILE_LINE_SIZE
to read each line of the configuration
file. By default this constant is set to 2048
that should be
enough for most applications. If your application uses configuration
files with lines that are longer, you can compile the generated C file
by specifying an explicit value for this constant with the -D
command line option of gcc
.
If an option is specified as multiple
, then it can be specified multiple
times at command line. In this case, say the option is called foo
, the
generated foo_given
field in the args structure contains the number of
times it was specified and the generated field foo_arg
is an array
containing all the values that were specified for this option.
Notice that if a default value is specified for a multiple option, that
value is assigned to the option only if no other value is specified on
the command line (and the corresponding _given
field will be set to 1),
i.e., a default value IS NOT always part of the values of a multiple
option.
For instance, if the gengetopt file is as follows
# test options that can be given more than once option "string" s "string option" string no multiple option "int" i "int option" int no multiple
Then the command line options can be collected like that
Then if this program is called with the following command line options
/* test options that can be given more than once */ #include <stdlib.h> #include <stdio.h> #include "test_multiple_cmd.h" static struct gengetopt_args_info args_info; int main (int argc, char **argv) { int i = 0; if (test_multiple_cmd_parser (argc, argv, &args_info) != 0) exit(1) ; for (i = 0; i < args_info.string_given; ++i) printf ("passed string: %s\n", args_info.string_arg[i]); for (i = 0; i < args_info.int_given; ++i) printf ("passed int: %d\n", args_info.int_arg[i]); return 0; }
The output of the program will be
passed string: world passed string: hello passed string: bar passed string: foo passed int: 200 passed int: 100
You can also pass arguments to a multiple option separated by commas, as in the following:
./test_multiple -s"foo","bar","hello" -i100,200 -s "world"
If you use gengetopt to generate C functions for parsing command line
arguments you have to know that these generated functions use
getopt_long
to actually read the command line and parsing it.
This function is typically part of the standard C library, but some
implementations may not include it. But this is not a problem: we
provide C files that actually implement getopt_long function:
getopt.c getopt1.c and gnugetopt.h. You'll find
these files in the <install prefix>/share/gengetopt directory
where <install prefix> is the one you specified during
compilation. If no prefix had been specified, /usr/local is the
default. If you downloaded gengetopt in binary form prefix will
probably be /usr/local or /usr.
You can rename gnugetopt.h to getopt.h and then simply compile these files and link them to the executable of you program. However, if you use automake and autoconf here's a more elegant solution: you should download the macro you find at this URL:
http://www.gnu.org/software/ac-archive/m4source/adl_func_getopt_long.m4
and add it to your acinclude.m4. You can find this macro also in the acinclude.m4 in the sources of gengetopt.
This macro checks if getopt_long function is in C library;
if it is not then it adds getopt.o and getopt1.o to the objects files
that will be linked to your executable (LIBOBJS
).
Then in Makefile.am of your source directory you have to add the contents
of LIBOBJS
to the LDADD
of the program that has to use getopt_long;
e.g., if the program foo has to use getopt_long, you have to add
the following line
foo_LDADD = @LIBOBJS@
Now these files will be compiled and linked to your program only if necessary.
Moreover you have to add getopt.c getopt1.c and
gnugetopt.h to your distribution. Note that it is not necessary
to put these file names among the foo_SOURCES
contents), but you have to
add gnugetopt.h to EXTRA_DIST
:
EXTRA_DIST = gnugetopt.h
You may want to take a look at gengetopt's configure.in and src/Makefile.am: they both use the techniques described here.
If you find a bug in gengetopt, please send electronic mail to
bug-gengetopt at gnu dot org
Include the version number, which you can find by running `gengetopt --version'. Also include in your message the output that the program produced and the output you expected.
If you have other questions, comments or suggestions about gengetopt, contact the author via electronic mail (find the address at http://www.lorenzobettini.it). The author will try to help you out, although he may not have time to fix your problems.
The list of todos in the TODO.
The following mailing lists are available:
help-gengetopt at gnu dot org
for generic discussions about the program and for asking for help about it (open mailing list), http://mail.gnu.org/mailman/listinfo/help-gengetopt
info-gengetopt at gnu dot org
for receiving information about new releases and features (read-only mailing list), http://mail.gnu.org/mailman/listinfo/info-gengetopt.
If you want to subscribe to a mailing list just go to the URL and follow the instructions, or send me an e-mail and I'll subscribe you.
--full-help
: Basic Usage-h,--help
: Basic Usage-V,--version
: Basic Usage[1] Command lines that are
too long are split into multiple indented lines separated by a \
.
Of course these commands are to be given in one line only, anyway.
[2] Since version 2.15.
[3] Since version 2.16.
[4] This holds since version 2.15: in previous versions the option specifications had to be given in a fixed order.
[5] Since version 2.16.
[6] The <option>_orig
was introduced in the release
2.14.
[7] This function was introduced in the release 2.14.