Search code examples
cgetopt-long

Mandatory options with getopt_long() in C


With C/ C++, getopt_long() can be used to parse command line arguments. Is it possible to tell the function that some of the options are mandatory? For example, how can I tell getopt_long that the parsing should give error if startServer is called without mentioning the port below?

./startServer -port 80

Note: I am not talking of option arguments as mandatory but rather the options themselves.


Solution

  • getopt_long() is not part of the C language. It is a GNU invention which is available in some C implementations, but far from all.

    The version of getopt_long() in glibc (used in most Linux distributions) does not allow you to specify that an option is mandatory. You'll have to check them explicitly after you're done parsing the command line.