Parse Long Options with getopt_long
Use getopt_long in C to accept --name and --name=value options, fill in the option table, handle flags and abbreviations, and keep short options working.

Short options such as -v are quick to type and impossible to remember. A script that runs tool -z -q -r tells the next reader nothing, while tool --compress --quiet --recursive explains itself. GNU tools popularised long options, and the same parser is in glibc 2.40, musl and every BSD as getopt_long. This post shows how to use it: the option table, the four ways a long option can carry a value, the pointer trick that sets a flag without a switch case, and the habits that keep scripts working. It extends parsing short options with getopt and is part of the guide to command-line tools in C.
What getopt_long adds
getopt_long is declared in <getopt.h>, not <unistd.h>. It is a superset of getopt: it handles every short option the same way, and it adds options introduced by two hyphens. The prototype is:
int getopt_long(int argc, char *const argv[], const char *optstring,
const struct option *longopts, int *longindex);The fourth argument is a table describing the long options, and the fifth is an optional pointer that receives the table index of the option that matched. The function is a GNU extension, not part of POSIX.1-2024, but it is available on all the systems you are likely to target. See getopt_long(3).
The option table
The table is an array of struct option ending with an entry of zeros. Each entry has four fields.
| Field | Meaning |
|---|---|
name | The long option name without the hyphens |
has_arg | no_argument (0), required_argument (1) or optional_argument (2) |
flag | If not NULL, a pointer to an int that is set to val when this option is found |
val | The value to return, or to store through flag |
The usual convention is to give each long option the same val as its short twin, so the switch handles both spellings in one case. Options with no short twin use a number above 255, so they cannot collide with a character.
#include <getopt.h>
enum { OPT_NO_COLOR = 256, OPT_TIMEOUT };
static int verbose_flag;
static const struct option long_options[] = {
{ "output", required_argument, NULL, 'o' },
{ "count", required_argument, NULL, 'n' },
{ "verbose", no_argument, &verbose_flag, 1 },
{ "quiet", no_argument, NULL, 'q' },
{ "no-color", no_argument, NULL, OPT_NO_COLOR },
{ "timeout", optional_argument, NULL, OPT_TIMEOUT },
{ "help", no_argument, NULL, 'h' },
{ NULL, 0, NULL, 0 }
};The verbose entry shows the flag trick. Because flag is not NULL, getopt_long writes 1 into verbose_flag and returns 0, so the loop needs no case for it. The trick suits plain on-off settings. For anything that needs more than setting a variable, return a character and handle it in the switch.
A complete program
The loop is the same shape as with getopt. The only change is the function and the extra arguments. The short option string, "o:n:qh", lists the letters that still work as short options.
#define _GNU_SOURCE
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
enum { OPT_NO_COLOR = 256, OPT_TIMEOUT };
static int verbose_flag;
static const struct option long_options[] = {
{ "output", required_argument, NULL, 'o' },
{ "count", required_argument, NULL, 'n' },
{ "verbose", no_argument, &verbose_flag, 1 },
{ "quiet", no_argument, NULL, 'q' },
{ "no-color", no_argument, NULL, OPT_NO_COLOR },
{ "timeout", optional_argument, NULL, OPT_TIMEOUT },
{ "help", no_argument, NULL, 'h' },
{ NULL, 0, NULL, 0 }
};
int main(int argc, char *argv[])
{
const char *outfile = "-";
long count = 1;
int quiet = 0, color = 1;
const char *timeout = "none";
int opt;
while ((opt = getopt_long(argc, argv, "o:n:qh", long_options, NULL)) != -1) {
switch (opt) {
case 0:
break;
case 'o': outfile = optarg; break;
case 'n': count = strtol(optarg, NULL, 10); break;
case 'q': quiet = 1; break;
case OPT_NO_COLOR: color = 0; break;
case OPT_TIMEOUT: timeout = optarg ? optarg : "30"; break;
case 'h':
puts("usage: longopts [options] [file ...]");
return 0;
default:
fprintf(stderr, "try '%s --help'\n", argv[0]);
return 2;
}
}
printf("output=%s count=%ld quiet=%d color=%d verbose=%d timeout=%s\n",
outfile, count, quiet, color, verbose_flag, timeout);
for (int i = optind; i < argc; i++)
printf("operand: %s\n", argv[i]);
return 0;
}Running ./longopts --output=out.txt --count 5 --verbose --no-color --timeout a.txt prints:
output=out.txt count=5 quiet=0 color=0 verbose=1 timeout=30
operand: a.txtThe same command written with short options and attached values, ./longopts -oout.txt -n5 -q a.txt, prints:
output=out.txt count=5 quiet=1 color=1 verbose=0 timeout=none
operand: a.txtShort and long forms share one set of variables, which is the point of mapping them to the same return values.
How a long option takes a value
There are three has_arg modes, and the way the user supplies the value differs.
required_argument: the value follows after an equals sign,--count=5, or in the next word,--count 5. Both forms work.optional_argument: the value must be attached with an equals sign,--timeout=10. The next word is never taken as the value. In the example above,--timeout a.txtleavesa.txtas an operand andoptargisNULL, so the program's default of 30 applies.no_argument:--verbose=yesis an error.getopt_longprintsoption '--verbose' doesn't allow an argument.
That optional-argument rule is the one that surprises people, and it is reason enough to avoid optional_argument in tools used by many people. A required argument with a clear default in the help text is easier to explain.
Abbreviations and why scripts should not use them
glibc accepts any unambiguous prefix of a long option. --out=x matches --output, and --no-c matches --no-color. If a prefix could match more than one option, the parser prints an error that the option is ambiguous and returns '?'. An exact match always wins over a longer name that merely starts with it.
That is convenient at a keyboard and risky in a script. Today --ver means --verbose. If a later release adds --version, the same script fails with an ambiguity error. The advice is to write full names in scripts and in documentation, and to remember when adding an option that you may be breaking someone's abbreviation. Neither musl nor the BSD implementations is guaranteed to accept abbreviations in the same way, so do not rely on them for portability either.
Telling which option matched
The fifth argument gives you the table position of the matched long option. Pass the address of an int and read it after the call when the same val is shared by several names, or when you want the name for a message:
int idx = 0;
while ((opt = getopt_long(argc, argv, "o:n:qh", long_options, &idx)) != -1) {
if (opt == 'n')
fprintf(stderr, "count set via %s\n",
idx ? long_options[idx].name : "short option");
}The index is only meaningful for a long option. For a short option the variable is left unchanged, so reset it to 0 before the call if you read it, as shown. Most programs never need it, and passing NULL is the norm.
Errors and the leading colon
Errors work as with getopt. By default the parser prints a message such as unrecognized option '--colour' and returns '?'. Setting opterr = 0, or starting the option string with a colon, suppresses the message. With a leading colon, a long option that lacks a required value returns ':' and sets optopt to the option's val, the same as for a short one. A good tool still tells the user what to do next, which is why the example prints a --help hint after the parser's own message.
Keeping the help text and the table in step
The help text and the table describe the same options, and they drift apart. One way to hold them together is to generate the help from the table plus a parallel array of descriptions, so adding an option in one place cannot forget the other. For a small tool, a unit test that parses every option listed in --help output works too. Either way, make --help print to standard output and exit 0, and make the usage error go to standard error and exit 2, as explained in the hub guide.
What to avoid
Four habits keep tools predictable.
Do not reuse a long name with a different meaning from the common tools. Users expect
--helpand--versionto exist and to do nothing else, and--verbose,--quietand--dry-runto mean what they say.Do not make every option take an optional argument. The attached-value rule will cost your users time.
Do not rely on abbreviations in scripts or examples.
**Do not use
getopt_long_only,** a variant that lets long options start with a single hyphen. It makes-cambiguous between a short option and the start of a long one, and it breaks bundling.


