C++ CLI Template sample (argument processing without getopts)  
C++ CLI Template sample (argument processing without getopts)
Jan 20, 2012
6:49:04 pm

If you've ever had the need to make a C++ CLI application and just want to put something together quickly, you probably want to take in arguments from terminal. All right, but then you have to write all that out. I know it's trivial, but I hate writing that out every time. So here's a template to make your lives easier.

It uses boost libraries.

main.cpp

#include <string>
#include <boost/program_options.hpp>

using namespace std;
using namespace boost::program_options;

void print_help(options_description desc, string app_name) {
    cout << app_name << " [options]" << endl;
    cout << "\tList what the application does here." << endl;
    cout << "Options:" << endl;
    desc.print(cout);
    cout << endl << endl << "Example:" << endl;
    cout << "\t" << app_name << " sample command" << endl << endl;
}

int main (int argc, char * const argv[]) {
    //some docs first
    options_description desc;
    desc.add_options()
        ("help", "Shows this help message.")
        ("sample", value<string>(), "A sample thing.")
        ;

    //read the options
    variables_map vm_arg;
    store(parse_command_line(argc, argv, desc), vm_arg);
    notify(vm_arg);
    
    if (vm_arg.find("help") != vm_arg.end() || argc == 1) {
        print_help(desc, argv[0]);
    }

    //do your stuff here

    return 0;
}

Like I said, this guy uses boost so your Makefile will need to include the boost lib. Here's mine:

Makefile

CC = /usr/bin/gcc
LNK_OPTIONS = \
        -L/usr/lib \
        -L/usr/local/lib \
        -Llib \
        -lboost_program_options-mt 
        
DEBUG_OUTPUT = 1;

#ifeq ($(UNAME), Darwin)
MACOSX_DEPLOYMENT_TARGET_i386 = 10.6
MACOSX_DEPLOYMENT_TARGET_x86_64 = 10.6
SDKROOT_i386 = /Developer/SDKs/MacOSX10.6u.sdk
SDKROOT_x86_64 = /Developer/SDKs/MacOSX10.6u.sdk
CC = /usr/bin/g++
#endif

#
# INCLUDE directories
#
INCLUDE = -I. -I/usr/include -I/usr/local/include -Iinclude

#
# Build cli_template
#

cli_template: 
        rm -f ./main.o;
        make ./main.o 
    $(CC) $(INCLUDE) $(LNK_OPTIONS) \
        ./main.o \
        -o build/Debug/cli_template 

clean: 
        rm -f \
        ./main.o 

install:
        make cli_template;
        cp build/Debug/cli_template /usr/local/bin/cli_template

#
# Build the parts of cli_template
#

# Item # 1 -- main --
./main.o: main.cpp
    $(CC) $(CC_OPTIONS) main.cpp -c $(INCLUDE) -o ./main.o

If anyone has something they use that is cleaner, I'd love to see it. This just goes fast for me.

to comment, login using [ google, twitter, facebook ]
0 comments