Component of the Week #33: balcl_commandline

Summary:
  • A class for representing and manipulating command line arguments in a platform-independent way. It is typically used to encapsulate the arguments passed to a program’s main(int argc, char *argv[]) function.

The balcl::CommandLine and its helper classes in the balcl package provide a convenient, flexible and robust means of parsing command-line arguments.

balcl::CommandLine is a very feature-rich facility, having far too much functionality to cover in a “Component of the Week” article. See the component documentation for a comprehensive description.

balcl::CommandLine allows:

  • Single-letter argument names - specified with a single dash, while supporting synonyms for them that are full words specified with a double-dash.

  • Boolean single-letter arguments can be combined - ie, ‘-a’ and ‘-b’ may be specified as “-ab” to set both

  • Unnamed positional arguments

  • Arguments may be specified by environment variables

  • Non-boolean arguments may be required or optional

  • Non-boolean arguments may be variable-length arrays

  • Non-boolean arguments may have default values

  • Support for automatic 'usage' message if arguments specified incorrectly

Basic Command Line Argument Parsing

#include <balcl_commandline.h>
#include <balcl_optioninfo.h>
#include <balcl_typeinfo.h>
#include <balcl_occurrenceinfo.h>
#include <bsl_iostream.h>
#include <bsl_fstream.h>
#include <bsl_string.h>

using namespace BloombergLP;
using bsl::cout;
using bsl::endl;

int main(int argc, char *argv[])
{
    // Variables to hold option values
    bool        helpFlag    = false;
    int         countValue  = 0;
    bsl::string outputFile;

    // Table of option metadata
    balcl::OptionInfo optionInfos[] = {
        {
            "h|help",
            "help",
            "Display Program Help Information",
            balcl::TypeInfo(&helpFlag),
            balcl::OccurrenceInfo(),
            ""
        },
        {
            "c|count",
            "count",
            "Number of times to run",
            balcl::TypeInfo(&countValue),
            balcl::OccurrenceInfo(),
            ""
        },
        {
            "o|output",
            "output",
            "Output file name",
            balcl::TypeInfo(&outputFile),
            balcl::OccurrenceInfo::e_REQUIRED,
            ""
        }
    };

    // Construct CommandLine with options and arguments
    balcl::CommandLine cmdLine(optionInfos);

    if (cmdLine.parse(argc, argv) || helpFlag) {
        cmdLine.printUsage();
        return helpFlag ? 0 : -1;                                  // RETURN
    }

    cout << "helpFlag: "   << helpFlag   << endl;
    cout << "countValue: " << countValue << endl;
    cout << "outputFile: " << outputFile << endl;

    bsl::fstream output(outputFile.c_str(), bsl::ios::out);
    BSLS_ASSERT(output.is_open());

    // Produce output ...

    return 0;
}

For More Information See Also