Most Linux programs allow the user to specify command-line options. Such options perform a wide variety of functions but are fairly uniform in their syntax. Short options consist of a - character followed by a single alphanumeric character. Long options, common in GNU utilities, consist of two - characters followed by a string made up of letters, numbers, and hyphens. Either type of option may be followed by an argument. A space separates a short option from its arguments; either a space or an = separates a long option from an argument. There are many ways of parsing command-line options. The most popular method is parsing the argv array by hand. The library functions getopt() and getopt_long() provide some assistance for option parsing. getopt() is provided by many Unix implementations, but it supports only short options. The getopt_long() function is available on Linux and allows automated parsing of both short and long options.[1] [1] The glibc library also provides the argp library, which provides yet another alternative for option parsing. A library called popt exists specifically for option parsing. It includes a number of advantages over the getopt() functions. It does not make use of global variables, which allows it to be used when multiple passes are needed to parse argv. It can parse an arbitrary array of argv-style elements. This allows popt to be used for parsing command-line-style strings from any source. Many argument types can be parsed by the library without any extra code in the application. It provides a standard method of option aliasing. Programs that use popt can easily allow users to add new command-line options, which are defined as combinations of already-existing options. This allows the user to define new, complex behaviors or change the default behaviors of existing options. There is a straightforward mechanism for allowing libraries to parse some options while the main application parses other options. It can automatically generate a usage message summarizing the options a program understands, as well as a more detailed help message. Common error messages are provided by the library. Like getopt_long(), the popt library supports short and long style options. The popt library is highly portable and should work on any POSIX platform. The latest version is available from ftp://ftp.rpm.org/pub/rpm/. There are some features of popt that we do not discuss in this chapter, but the popt man page is quite good and contains documention on the features we have skipped. It may be redistributed under either the GNU General Public License or the GNU Library General Public License, at the distributor's discretion. |