3 ms·
Another option with similar levels of macro (ab)use is my "magic getopt" which lets you write code like this: const char * ch; while ((ch = GET
by cperciva 4y ago
Another option with similar levels of macro (ab)use is my "magic getopt" which lets you write code like this:
const char * ch;
while ((ch = GETOPT(argc, argv)) != NULL) {
GETOPT_SWITCH(ch) {
GETOPT_OPT("-a"):
aflag = 1;
break;
GETOPT_OPTARG("--bar"):
printf("bar: %s\n", optarg);
break;
GETOPT_OPTARG("-f"):
printf("foo: %s\n", optarg);
break;
GETOPT_MISSING_ARG:
printf("missing argument to %s\n", ch);
/* FALLTHROUGH */
GETOPT_DEFAULT:
usage();
}
}
- chungy 4y agoswitch options falling through doesn't seem like magic to me. Rather, a common practice.
- cperciva 4y agoThat's not the magic part...
- ufo 4y agoI'm intrigued. Is there somewhere where we could find the full definition of these macros?
- cperciva 4y agohttps://github.com/Tarsnap/libcperciva/blob/master/util/getopt.h https://github.com/Tarsnap/libcperciva/blob/master/util/geto... https://github.com/Tarsnap/libcperciva/blob/master/util/getopt.c https://github.com/Tarsnap/libcperciva/blob/master/util/geto... BSD licensed, of course.
- ZephyrP 4y agoVery neat. Do you implement option parsing in "magic getopt" or can you (somehow?) handle setting up the option string arguments used by the more familiar variants in getopt(3)?
- cperciva 4y agoAll the option parsing is done in functions called by the macros. The "getopt string" isn't needed since the GETOPT_OPT() and GETOPT_OPTARG() "case statements" convey the same information (the set of valid options).