getopt_long -- parse command line options


#define _GNU_SOURCE
#include <getopt.h>

int getopt_long(int argc, char * const argv[], const char * opstring, const struct option * longopts, int * longindex);


getopt_long() works like getopt() except that it also accepts long options, started out by two dashes. Long option names may be abbreviated if the abbreviation is unique or is an exact match for some defined option. A long option may take a parameter, of the form --arg=param or --arg param.

longopts is a pointer to the first element of an array of struct option declared in getopt.h as:

  struct option {
             const char *name;
             int has_arg;
             int *flag;
             int val;

The fields in this structure have the following meaning:


The name of the long option.


One of:

no_argument (or 0) if the option does not take an argument,
required_argument (or 1) if the option requires an argument, or
optional_argument (or 2) if the option takes an optional argument.


specifies how results are returned for a long option. If flag is NULL, then getopt_long() shall return val. (For example, the calling program may set val to the equivalent short option character.) Otherwise, getopt_long() returns 0, and flag shall point to a variable which shall be set to val if the option is found, but left unchanged if the option is not found.


The value to return, or to load into the variable pointed to by flag.

If longindex is not NULL, it points to a variable which is set to the index of the long option relative to longopts.

Return Value

getopt_long() returns the option character if a short option was found successfully, or ":" if there was a missing parameter for one of the options, or "?" for an unknown option character, or -1 for the end of the option list.

For a long option, getopt_long() returns val if flag is NULL, and 0 otherwise. Error and -1 returns are the same as for getopt(), plus "?" for an ambiguous match or an extraneous parameter.