This article is part number 6 of the CLI design series.


In the previous post, we saw what good and bad use cases for flags in the interface of a command-line application are. We talked about the theory, so it is now the time to talk about the implementation details.

The point I want to make in this post is simple: do not reinvent option parsing. Use the libraries provided by the platform you are targeting to implement the interface of your application: even if there is some little detail of the library that you don’t agree with, consistency with the platform is lightyears better than a custom implementation that fails to handle some corner cases and/or behaves in an unexpected manner.

Framework-less tools for Unix

The interface that you use to implement option parsing in a console-based, framework-less application for Unix depends on the language you are using and the libraries you are targeting. Let’s take a look at a few specific examples:

  • C: If all you have access to (or want to depend on) is the standard C library, the only choice you have is to use the getopt(3) and getopt_long(3) library functions. The former is a POSIX standard while the latter isn’t but is widely available.

    There also is AutoOpts, which is a powerful option parser and a documentation generator from the options descriptor.

  • C++: In this case, you can use the same interfaces as you use for C. However, if you use the popular Boost libraries, you can use Boost.Program_options for a native C++ interface. Be aware that the semantics are slightly different, partly because this library is portable to Windows.

  • Shell: Use the getopts builtin function of the shell interpreter to handle option parsing. Avoid using the external getopt(1) utility as it cannot handle whitespace in arguments properly. Note that none of these two interfaces support processing long-style flags; if you want to deal with those, you probably need to implement your own parsing. If you do, try to follow the interface of getopt_long as much as possible.

  • Python: Just use the argparse module (and not optparse, which is deprecated).

Tools for GNOME

If you are writing an application that integrates with the GNOME desktop environment, or an application that uses a subset of the libraries provided by this platform, use the Commandline option parser of Glib. Note that Glib is not a graphical library, so you can even use it for your console-based utilities that don’t need access to the graphics environment.

Tools for KDE

Similarly to the GNOME applications, the KDE platform provides its own option parsing library for C++. Use the KCmdLineArgs class to perform your option-parsing tasks.


What do you think? Did I miss some important and standard mechanism to parse options? If so, which one?

Comments from the original Blogger-hosted post: