Argument-parsing helpers for C/Unix

2019-01-07 06:47发布

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++?

7条回答
我想做一个坏孩纸
2楼-- · 2019-01-07 07:19

Since I was looking for the same thing, I read the answers of this old topic. Finally I chose dropt which is mentioned in What parameter parser libraries are there for C++?. Actually it's implemented in C, so I think it's worth mentioning here as well. I haven't used the C++ helper, which wraps the C implementation.

Interesting facts about dropt:

  • Lightweight
  • Depends only on standard libs
  • No steep learning curve
  • Sufficient for basic arg parsing, plus a couple of powerful features
  • Easy to extend
  • Unrestrictive license (zlib-ish)

It is limited though. For instance, I had to adapt my parameters syntax specifications a little; that was acceptable in this very case, but of course sometimes specifications are carved in stone.

As a conclusion I would recommend dropt at least for fast prototyping, tools development, and in-house projects.

查看更多
登录 后发表回答