Tuesday, December 04, 2007

TCLAP for developing CLI in C++

I am faced with the task of parsing command line argument many times quite often, probably almost as often as I make programs itself. Even when we don't intend to pass anything to our program, e.g: it's a GUI program, we usually end up coding argument handling part too eventually. So, I guess it's a homework of every professional programmer to find himself a CLI argument parser library/tool he can rely on.

For me, in C++, TCLAP is that tool. It took me some searching and exploring to finally find and settle with it. I tried things from emulating other existing codes, trying several library with couple problems (license, ease of use, maintainability, maturity of the library). When I tried TCLAP it was like "this is it, it's quite good, I'll stick with it". And now, years has passed since I first using it and I don't have any need to use anything else so far, so I guess it's not just "quite good" library but a really good, easy-to-use one.

Here's a brief snippet to give picture on how it works

2:CmdLine cmd("myProgram", ' ', VERSION);
4:ValueArg<int> arg0("","arg0","Description",true, 0, "Type Description");
5:cmd.add( arg0 );
7://NOTE : more params
10: cmd.parse( argc, argv );
11:} catch (ArgException &e) //NOTE : catch any exceptions
13: std::cerr << "error: " << e.error() << " for arg " << e.argId() << endl;
14: exit(1);
17://NOTE : use any arg.getValue() here like any variable

The code looks really straightforward : make a CmdLine object, add argument objects to it, call parse(), then use the values. It avoids us to have to do nasty parsing or converting that take space and add complexity in our code.

I think this one will still be on my toolbox for a long time.

No comments: