Which command line parser for C++ apps ?

If you need to parse command line arguments in C++, don’t reinvent the wheel, use an existing library. That’s the kind of problem that seems so simple that it’s obvious you’ll quickly hack it. Then you face parsing bugs, spaces within parameters, special characters, optional parameters, config files, etc. Eventually you’ll switch to a library, so save time and do it from the beginning.

Many libraries are available out there for C++ applications, I’ll focus on two of them : Boost.Program_options and GetPot.

Boost.Program_options

That’s the Rolls Royce of commande line parameters parsers :

  • supports all possible syntaxes (unix style, Windows style, custom style)
  • supports both configuration files and command line parameters
  • generates the command line help automatically
  • etc

[code lang=”cpp”]
// Example of a BOOST program_options parameters parsing
po::options_description desc(“Allowed options”);
desc.add_options()
(“help”, “produce help message”)
(“nosplash”, po::value(), “disables splash screen”)
(“username”, po::value(), “user name”);

po::variables_map vm;
po::store(po::parse_command_line(ac, av, desc), vm);
po::notify(vm);

if (vm.count(“username”)) {
print(“User name specified : %s”, vm[“username”]);
}

[/code]

There’s just one drawback : contrary to many BOOST library, using Program_options is not as simple as including a header. You need to link with the corresponding library.
You should already be using BOOST in your project, so that shouldn’t be a problem. But if you’re not (because, for example, you have to use a 20 years old compiler, like I recently had to), or if you don’t want to add BOOST just for the sake of parsing parameters because it would be like using a sledgehammer to crack a nut, you may want to fall back on a simpler, self contained solution.

GetPot

GetPot may not offer all the bells and whistles you’ll find with BOOST, but it has what matters (config files, etc.), it’s simpler to use and selfcontained in a header file. Morevover, it’s very well documented,  you’ll be up an running in a matter of minutes.

[code lang=”Cpp”]
// Example of Parameter parsing with GetPot
#include “GetPot”
#include
#include

using namespace std;

int main(int argc, char** argv)
{
GetPot paramParser(argc, argv);

bool noSplashScreen = paramParser.search(“–nosplash”);

string username;
if (paramParser.search(2, “–user”, “-u”))
{
username = paramParser.next(“”).c_str();
}
}

[/code]

Leave a Reply

Your email address will not be published. Required fields are marked *