Switch branches/tags
Nothing to show
Find file History
Failed to load latest commit information.
opt.c touchups Jul 31, 2012


A sane implementation of command line argument parsing. It is greatly 
inspired by Go's standard library 'flag' package.

(I really couldn't believe how horrendous 'getopt' was, and the Internet seems 
to expect me to use it since it's so ubiquitous. I found this distasteful, 
particularly as someone who has been spoiled with Python's 'argparse' module, 
and Go's 'flag' package.)

`libopt` can be used by compiling with `-lopt`, assuming that 'opt.h' and
'libopt.so' are in your C_INCLUDE_PATH and LIBRARY_PATH, respectively.

'libopt.so' can be generated by running 'make'. The only dependency is glibc.

libopt is pretty simple in that it only allows flags specified by a '--' prefix.
(That means short flags like '-a' aren't currently supported, but are on the 
TODO list.) Four different kinds of flags can be specified: bool, int, double 
or string. 

A small example showing how to add an int flag and read all of the
non-flag arguments:

    #include <stdio.h>

    #include "opt.h"

    int main(int argc, char **argv)
        struct opt_config *conf;
        struct opt_args *args;
        int flag_num, i;

        conf = opt_config_init();
        opt_flag_int(conf, &flag_num, "num", 0, "Usage info for flag 'num'.");
        args = opt_config_parse(conf, argc, argv);

        printf("flag num is: %d\n", flag_num);
        printf("number of non-flag arguments: %d\n", args->nargs);
        for (i = 0; i < args->nargs; i++)
            printf("\targ %d: %s\n", i, args->args[i]);

        opt_config_free(conf, args);

        return 0;

The example can be found in `examples/simple.c`. A slightly larger example 
showing how to use the rest of the argument types can be found in