I've done some looking and there are a whole lot of libraries for command line option parsing, but it is difficult to differentiate between them. Does anyone have any experience with any of them? Is one harder/better/faster/easier/whatever than any of the others? Or should I just grow my own?
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With