creating command-line parser

Notice that almost all linux programs have command-line options, you can pass in the arguments to your programs. Some common arguments such as:

dummy -v
dummy --help

So there is two type of options, long and short. In linux (probably unix based os as well), we have getopt functions to help us for this. See the simple examples as bellow:


int main(int argc, char *argv[])
    int gnDebug=0;

        int option_index = 0;
        int optchr;

        static struct option long_options[4] = {
            {"debug", 0,0,0},

        optchr=getopt_long(argc, argv ,"hvV", long_options, &option_index);
        switch (optchr)
            case 0:
                    if (gnDebug)
                        printf("[Debug Mode Off]\n");
                        printf("[Debug Mode Set]\n");
            case 'v':
            case 'V':
                printf(" 0.1\n");
                return 0;
            case 'h':
                printf(" %s -v Check binary version\n",argv[0]);
                printf(" %s -h Display this help\n",argv[0]);
                return 0;
        }//end switch
    }//end while

    return 0;

First of all construct your long options array from option structure. First element is the long name, second element is to indicate whether the long option takes any arguments. Its like if you want to do this

dummy --debug 2

2 is an argument of long option debug. And the last element of struct is the equivalent of short option. You do not need to write twice of the execution code for the same option.

Next, call getopt_long, the third parameter is to list all short options. And the rest should be easy to understand. If you only need to specified short option, don’t use getopt_long, use getopt instead.


2 thoughts on “creating command-line parser

  1. Pingback:

Leave a Reply

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