Possible Duplicate:
getopt_long() — proper way to use it?
I'm struggling with getopt_long in my C program. Code:
const struct option long_options[] = {
{ "help", 0, NULL, 'h' },
{ "num", 1, NULL, 'n' },
{ NULL, 0, NULL, 0 }
};
do {
next_option = getopt_long(argc, argv, short_options,
long_options, NULL);
switch(next_option) {
case 'h':
print_usage(stdout, 0);
case 'n':
printf("num %s\n", optarg);
break;
case '?':
print_usage(stderr, 1);
break;
default:
abort();
}
} while(next_option != -1);
This works:
./a.out --num 3
num 3
This works (why?!):
./a.out --n 3
num 3
This does not:
./a.out -n 3
num (null)
so long option works, short does with two '-'s (why?) and the short option doesn't work (printf
prints NULL
), why is this? Many thanks.
you need to pass a short options string too, something like this:
const char *short_options ="hn:";
Note the :
means -n
accepts an argument.