Site Tools


h-getopt

**This is an old revision of the document!**

<getopt.h>

<getopt.h> (POSIX/GNU) provides getopt for short options (-v, -o file) and getopt_long for long options (--verbose, --output=file). It handles argument parsing, optarg tracking, and stops at the first non-option argument or --.

Use it to parse command-line arguments portably instead of handling argv manually.

Example

This example parses both short and long options, handling argument requirements.

// compile: gcc -o getoptexample getoptexample.c
// run: ./getoptexample -v --output=out.txt file1.txt
// description: parse short and long options with arguments
 
#include <getopt.h>
#include <stdio.h>
 
int main(int argc, char* argv[]) {
    int verbose = 0;
    const char* outfile = "a.out";
    int c;
 
    struct option opts[] = {
        {"verbose", no_argument, NULL, 'v'},
        {"output", required_argument, NULL, 'o'},
        {0, 0, 0, 0}
    };
 
    while ((c = getopt_long(argc, argv, "vo:", opts, NULL)) != -1) {
        switch (c) {
        case 'v': verbose = 1; break;
        case 'o': outfile = optarg; break;
        case '?': return 1;
        }
    }
 
    printf("verbose=%d output=%s\n", verbose, outfile);
    for (int i = optind; i < argc; i++)
        printf("  input: %s\n", argv[i]);
    return 0;
}

Common functions and variables

Short option parsing:

  • getopt(argc, argv, optstring) — parse options (GNU extension, POSIX)
    • optstring format: "ab:c::" means -a (no arg), -b (required arg), -c (optional arg)
    • Returns option character, ? on error, : on missing arg, or -1 when done
    • Resets on each call with new argv

Long option parsing:

  • getopt_long(argc, argv, optstring, longopts, &longindex) — parse long options
  • struct option { const char *name; int has_arg; int *flag; int val; };
    • Terminate array with {0, 0, 0, 0}
    • Long option matching: --verbose=value or --verbose value

Argument flags (for struct option.has_arg):

  • no_argument — option takes no argument
  • required_argument — option requires argument
  • optional_argument — argument is optional

Global variables (set by getopt):

  • optarg — pointer to argument for current option (NULL if none)
  • optind — index in argv of next element to process (initialize to 1)
  • opterr — if 1 (default), print error messages to stderr on unknown options
  • optopt — option character that caused error (unknown option or missing arg)

Usage pattern:

while ((opt = getopt_long(argc, argv, "abc:d::", longopts, &idx)) != -1) {
    switch (opt) {
        case 'a': /* handle -a */ break;
        case 'c': /* optarg has argument */ break;
        case 'd': /* optional arg in optarg */ break;
        case 0:   /* long option, check longopts[idx] */ break;
        case '?': /* unknown option or missing arg */ break;
    }
}
 
// argv[optind] is first non-option argument
h-getopt.1787615735.md.gz · Last modified: by Ivan Janevski