Option Parsers for C/C++? [duplicate]

核能气质少年 提交于 2019-11-27 20:45:44

If you want something completely cross-platform, I've found the Boost::Program_Options library to be very good. There's something of a learning curve to setting it up, but once you master that, it simplifies things greatly.

Jonathan Leffler

For many purposes, the GNU getopt() and getopt_long() functions are good choices.

The GNU getopt() is for single-letter option arguments and hews fairly close to the POSIX standard behaviour, and can be persuaded to behave more orthodoxly by setting the environment variable POSIXLY_CORRECT. The difference is that GNU getopt() recognizes option arguments after the first non-option argument, and permutes the arguments so that all the option arguments are processed before any of the non-option arguments. This sometimes matters - though the contexts tend to be a little esoteric. There are a few other extra tricks available.

The GNU getopt_long() is the best mechanism for dealing with long-options such as --help. It can handle optional arguments, matching single-letter options and all sorts of things.

There are numerous other packages available that handle options in various ways.

(Perl has a plethora of Getopt modules, reflecting how much effort has been put in over the years.)

You might find some useful extra information at What is the general syntax of a Unix shell command. You can also read the POSIX specification for command line conventions in the Utility Conventions chapter.

boost::program_options is pretty good and has a nice C++ interface that can check that option parameters have a certain type (like 'int') and store them directly into variables.

It also supports to load the "options" from a config file, so you get a config file parser for free. This way you can very easily allow to override all the configuration settings from the command line or add all the command line options to the config file, which makes it very flexible.

also there are popt.

if you are using linux/unix then getopt is the option parser for you it. works on almost all flavors of unix and is easy to use

I use the system implementation of getopt_long() for most things, however you might need to be more portable which prohibits the use of such POSIX creature comforts.

Here is the standard regarding the POSIX view of command line options if you are in a position where getopt() / getopt_long() are just not available and need to roll your own. You might also want a look at what POSIX has to say about help / option summary displays (I can't find a link to that part of the standard off hand).

Personally, I don't like using programs that do not take --long-options, because remembering the short options is a pain and no two programs use the same.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!