Gimme Another Option boost::program_options simplifies your life (of developer)
24 August 2014
How to add options in your C++ using the boost::program_options library.
Boost is a collection of open-source and general-purpose libraries for C++. They solve a wide range of problems and are massively used in software development.
Every persone that consider himself a good C++ programmer, should know and master Boost libraries.
In this post I’ll show you how is easy add options to ours programs using Boost. Sometimes parse the input provided by the users can be complicated in case the input parameters do not depend on any position or can have abbreviations. Moreover, a good software should always have - -help that describe its correct usage and the meaning of the options.
Let’s try to write an easy program that is able to calculate the power or the logarithm of a number, depending on the type of argument provided:
power if base and exponent are present,
logarithm if base and number are present.
The first think to do is to include the program_options header and make an alias for the boost::program_options.
After this, is possible use an object of type opt::options_description that describes a number of options and call the method add_options. The syntax is preatty easy:
name to be used in command line
type of the option wrapped in value<> class
Is also possible define default using the method default_value(). In our case we can image to have 10 as default base.
At this point we need two variables to parse the command line and store the command line arguments:
As last thing, to check if an option is present or to get its value is enough to use the methods counts and as<T>():
At this point all the necessary has been explained. You can look at the final code below:
As last thing, we have to link the libboost_program_ options library because boost::program_options is not a header-only library: