Node:Processing command-line options, Next:Environment variables, Previous:argc and argv, Up:Putting a program together
Processing command-line options
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,
permits GNU-style long options (for example,
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
--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
interface makes implementing them easy.
- Command-line arguments are options if they begin with a hyphen (
- Multiple options may follow a hyphen in a cluster if they do not take
-a -b -care the same.
- Option names are single alphanumeric characters.
- Options may require an argument. For example, the
-ooption of the
ldcommand requires an output file name.
- The whitespace separating an option and its argument is optional.
-ofooare the same.
- Options usually precede non-option arguments. (In fact,
argpis more flexible than this; if you want to suppress this flexibility, define the
- The argument
--terminates all options; all following command-line arguments are considered non-option arguments, even if they begin with a hyphen.
- A single hyphen as an argument is considered a non-option argument; by convention, it is used to specify input from standard input or output to standard output.
- Options may appear in any order, even multiple times. The meaning of this is left to the application.
In addition, GNU adds long options, like the
--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
--verbose) often has a short-option synonym (such as
Long options can accept optional (that is, non-necessary) arguments.
You can specify an argument for a long option as follows:
You may not type whitespace between the option name and the equals sign, or between the equals sign and the option value.