Tony Finch – blog

submited by
Style Pass
2024-11-07 02:30:03

Most argument parsers are declarative: you tell them what to parse, and they do it. This one provides you with a stream of options and values and lets you figure out the rest.

For “pathologically simple” I still rather like getopt(3) despite its lack of support for long options. Aaron S Cohen wrote getopt in around 1979, and it was released into the public domain by AT&T in 1985. A very useful 50-ish lines of code! It still has almost everything required by POSIX nearly four decades later.

But the description of lexopt made me think getopt() could be simpler. The insight is that the string of options that you have to pass to getopt() is redundant with respect to the code that deals with the return values from getopt(). What if you just get rid of the options string?

My new code is half the size or less of getopt(), and has more functionality. I’m going to show how how this was done, because it’s short (ish), not because it is interesting. Then I’ll try to tease out a lesson or two.

Leave a Comment