C Posix-compliant argument parsing in 42 LoC, inspired by Duff's device
This uses switch abuse to handle short and long arguments in one place:<p><pre><code>    ...
    else if (ARG_LONG(&quot;option&quot;)) case &#x27;o&#x27;: {
    } ...

</code></pre>
The idea was to leave all the decisions to the library user, so there are no automatic help pages and error messages. The library essentially just gives you a new language primitive to work with.<p>Example usage (also included in the file):<p><pre><code>    &#x2F;&#x2F; assumes argv and argc exist

    ARG_BEGIN {
            if (0) {
                    case &#x27;a&#x27;: a = 1; ARG_FLAG(); break;
                    case &#x27;b&#x27;: b = 1; ARG_FLAG(); break;
                    case &#x27;c&#x27;: c = 1; ARG_FLAG(); break;
                    case &#x27;\0&#x27;: readstdin = 1; break;
            } else if (ARG_LONG(&quot;reverse&quot;)) case &#x27;r&#x27;: {
                    reverse = 1;
                    ARG_FLAG();
            } else if (ARG_LONG(&quot;input&quot;)) case &#x27;i&#x27;: {
                    input = ARG_VAL();
            } else if (ARG_LONG(&quot;output&quot;)) case &#x27;o&#x27;: {
                    output = ARG_VAL();
            } else if (ARG_LONG(&quot;help&quot;)) case &#x27;h&#x27;: case &#x27;?&#x27;: {
                    printf(&quot;Usage: %s [OPTION...] [STRING...]\n&quot;, argv0);
                    puts(&quot;Example usage of arg.h\n&quot;);
                    puts(&quot;Options:&quot;);
                    puts(&quot;  -a,                set a to true&quot;);
                    puts(&quot;  -b,                set a to true&quot;);
                    puts(&quot;  -c,                set a to true&quot;);
                    puts(&quot;  -r, --reverse      set reverse to true&quot;);
                    puts(&quot;  -i, --input=STR    set input string to STR&quot;);
                    puts(&quot;  -o, --output=STR   set output string to STR&quot;);
                    puts(&quot;  -h, --help         display this help and exit&quot;);
                    return EXIT_SUCCESS;
            } else { default:
                    fprintf(stderr,
                            &quot;%s: invalid option &#x27;%s&#x27;\n&quot;
                            &quot;Try &#x27;%s --help&#x27; for more information.\n&quot;,
                            argv0, *argv, argv0);
                    return EXIT_FAILURE;
            }
    } ARG_END;
   
    &#x2F;&#x2F; argv and argc now hold the non-option arguments</code></pre>