C/Unix 的参数解析助手 [英] Argument-parsing helpers for C/Unix
问题描述
我知道以下几点:
- 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)
我确定还有更多我没用过甚至听说过的;快速谷歌搜索显示 Gopt, argtable 和 Optlist.
I'm sure there's more that I haven't used or even heard of; a quick Google search reveals Gopt, argtable, and Optlist.
就我个人而言,我最喜欢 argp
,我使用 getopt
/getopt_long
编写的每个程序(超出了特定的复杂性基线)转换为使用 argp
.它比 popt
更广泛可用,比 getopt_long
更强大,文档齐全,与所有 GNU 风格的约定一致,并且非常灵活.不利的一面是,它远非最容易使用(由于如此灵活),而且支持它的代码非常冗长(C 中的许多东西也是如此).
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).
你用什么,为什么?
是的,我指的是 C 而不是 C++.有很多 C++ 解析器,但我不使用 C++.
Yes, I mean C rather than C++. There are a ton of C++ parsers, but I don't use C++.
John Millikin 指出 popt
不再维护.我列出它是因为许多程序仍在使用它——包括 AbiWord、rpm、rsync 和 samba——尽管 Gnome 努力 迁走.但我现在也添加了 Glib 参数解析器的链接.
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.
对于 C++ 参数解析,请参阅问题什么参数有 C++ 的解析器库吗?
For C++ argument parsing, see the question What parameter parser libraries are there for C++?
推荐答案
GNU 有 gengetopt它为选项数据结构和 getopt_long
代码生成代码以解析命令行并填充结构.. 它相当容易学习并且运行良好.
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.
它提供了 GNU 风格的语义(显然),并且足够小,如果您不确定您的受众的构建环境,它可以简单地包含在项目中进行分发.
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.
这篇关于C/Unix 的参数解析助手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!