Node:Processing command-line options, Next:Environment variables, Previous:argc and argv, Up:Putting a program together
It is easy, though tedious to pull options directly out of the
argv
vector with your own routines. It is slightly less tedious
to use the standard C option-processing function getopt
, or the
enhanced GNU version of the same function, getopt_long
, which
permits GNU-style long options (for example, --quiet
as
opposed to -q
).
The best option of all is to use the argp
interface for
processing options. Professionally written programs provide the user
with standard and useful options. The argp
function provides for
these. For the modest price of setting up your command line arguments
in a structured way, and with surprisingly few lines of code, you can
obtain all the perks of a "real" GNU program, such as
"automagically"-generated output to the --help
,
--usage
, and --version
options, as defined by the GNU
coding standards. Using argp
results in a more consistent
look-and-feel for programs that use it, and makes it less likely that
the built-in documentation for a program will be wrong or out of date.
POSIX, the Portable Operating System Interface standard, recommends the
following conventions for command-line arguments. The argp
interface makes implementing them easy.
-
).
-abc
and -a -b -c
are the same.
-o
option
of the ld
command requires an output file name.
-o foo
and -ofoo
are the same.
argp
is
more flexible than this; if you want to suppress this flexibility,
define the _POSIX_OPTION_ORDER
environment variable.)
--
terminates all options; all following command-line
arguments are considered non-option arguments, even if they begin with a hyphen.
In addition, GNU adds long options, like the --help
,
--usage
, and --version
options mentioned above. A
long option starts with --
, which is then followed by a string of
alphanumeric characters and hyphens. Option names are usually one to
three words long, with hyphens to separate words. Users can abbreviate
the option names as long as the abbreviations are unique. A long option
(such as --verbose
) often has a short-option synonym (such as
-v
).
Long options can accept optional (that is, non-necessary) arguments.
You can specify an argument for a long option as follows:
--
option-name=
value
You may not type whitespace between the option name and the equals sign, or between the equals sign and the option value.