Alesfatalis Alesfatalis - 1 year ago 111
C Question

getopt_long() option with optional argument

I am trying to create a option with an optional argument using getopt_long().

Here is my code:

static struct option long_options[] = {
{"help", no_argument, NULL, 'h'},
{"debug", no_argument, NULL, 'd'},
{"config", optional_argument, NULL, 'c'},
{NULL, 0, NULL, 0}

while ((ch = getopt_long(argc, argv, "hdc::", long_options, NULL)) != -1) {
// check to see if a single character or long option came through
switch (ch) {
case 'h': = true;
case 'd':
opt.debug = true;
case 'c':
printf("C-Option: %s\n", optarg);
if (optarg != NULL) {
opt.configFile = optarg;

I am trying to make the argument for
optional so you can run the program with these options:

-c test.cfg
optarg = "test.cfg"

optarg = null

If I set
is always

If I set
than I get an error:
option requires an argument -- 'c'

What did I wrong? Is there any other options I can set?

Answer Source

From the man pages:

If the option has an optional argument, it must be written directly after the option character if present.

Your code works as expected:

./a.out -c some_option --> "C-Option: (null)"
./a.out -csome_option --> "C-Option: some_option"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download