From ef504bfcc0a8867cdb06d8a9c7b8cd219d9f902a Mon Sep 17 00:00:00 2001 From: "David A. Pimentel" Date: Sat, 7 Feb 2026 14:52:28 -0700 Subject: [PATCH 1/2] Implement improved optional optarg parsing for long option. --- examples/long.c | 7 ++++++- optparse.h | 5 +++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/examples/long.c b/examples/long.c index 00993fa..4ba63b9 100644 --- a/examples/long.c +++ b/examples/long.c @@ -48,7 +48,12 @@ int main(int argc, char **argv) } } - /* Print remaining arguments. */ + printf("amend : %s\n", amend ? "true" : "false"); + printf("brief : %s\n", brief ? "true" : "false"); + printf("color : %s\n", color); + printf("delay : %d\n", delay); + + printf("Print remaining arguments:\n"); while ((arg = optparse_arg(&options))) printf("%s\n", arg); diff --git a/optparse.h b/optparse.h index 9b7c7f8..d1752cf 100644 --- a/optparse.h +++ b/optparse.h @@ -348,6 +348,7 @@ optparse_long(struct optparse *options, int *longindex) { int i; + char *next; char *option = options->argv[options->optind]; if (option == 0) { return -1; @@ -373,6 +374,7 @@ optparse_long(struct optparse *options, options->optopt = 0; options->optarg = 0; option += 2; /* skip "--" */ + next = options->argv[options->optind + 1]; options->optind++; for (i = 0; !optparse_longopts_end(longopts, i); i++) { const char *name = longopts[i].longname; @@ -392,6 +394,9 @@ optparse_long(struct optparse *options, return optparse_error(options, OPTPARSE_MSG_MISSING, name); else options->optind++; + } else if (longopts[i].argtype == OPTPARSE_OPTIONAL) { + if (next && next[0] != '-') + options->optarg = options->argv[options->optind++]; } return options->optopt; } From e83f4b6a0ebd4b914eac7428cb8464e4a753b27e Mon Sep 17 00:00:00 2001 From: "David A. Pimentel" Date: Sat, 7 Feb 2026 15:00:34 -0700 Subject: [PATCH 2/2] Add cpp guard --- optparse.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/optparse.h b/optparse.h index d1752cf..99d3288 100644 --- a/optparse.h +++ b/optparse.h @@ -394,9 +394,11 @@ optparse_long(struct optparse *options, return optparse_error(options, OPTPARSE_MSG_MISSING, name); else options->optind++; +#ifdef IMPROVED_OPTPARSE_OPTIONAL } else if (longopts[i].argtype == OPTPARSE_OPTIONAL) { if (next && next[0] != '-') options->optarg = options->argv[options->optind++]; +#endif } return options->optopt; }