Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argument-parsing helpers for C/Unix

I know of the following:

  • The venerable getopt(3)
  • The extended getopt_long
  • glibc's argp parser for Unix-style argument vectors
  • popt from the GNOME project (or its spiritual successor in Glib)

I'm sure there's more that I haven't used or even heard of; a quick Google search reveals Gopt, argtable, and Optlist.

Personally, I like argp best, and every program I wrote using getopt/getopt_long (beyond a certain baseline of complexity) has been converted to use argp. It's more widely available than popt, more powerful than getopt_long, well-documented, consistent with all the GNU-style conventions, and very flexible. On the downside, it's far from the easiest to use (thanks to being so flexible), and the code to support it is quite verbose (as are many things in C).

What do you use, and why?

Yes, I mean C rather than C++. There are a ton of C++ parsers, but I don't use C++.

John Millikin notes that popt is no longer maintained. I list it because many programs still use it -- including AbiWord, rpm, rsync, and samba -- despite Gnome's efforts to migrate away. But I've added a link to Glib's argument parser now, too.


For C++ argument parsing, see the question What parameter parser libraries are there for C++?

like image 507
ephemient Avatar asked Oct 10 '08 02:10

ephemient


People also ask

What is getopt in C?

The getopt() is one of the built-in C function that are used for taking the command line options. The syntax of this function is like below − getopt(int argc, char *const argv[], const char *optstring) The opstring is a list of characters. Each of them representing a single character option.

What is Optarg C?

optarg indicates an optional parameter to a command line option. opterr can be set to 0 to prevent getopt() from printing error messages. optind is the index of the next element of the argument list to be process, and optopt is the command line option last matched.

What are argv and argc in C?

argc stands for argument count and argv stands for argument values. These are variables passed to the main function when it starts executing.


1 Answers

GNU has gengetopt which generates code for an options data structure and the getopt_long code to parse the command line and fill the structure.. It's fairly easy to learn and works well.

As a bonus you can pass the options structure around your code and avoid global storage if desired.

It provides GNU style semantics (obviously), and is small enough to simply include with the project for distribution if you're not sure of your audience's build environment.

like image 87
dmckee --- ex-moderator kitten Avatar answered Sep 18 '22 17:09

dmckee --- ex-moderator kitten