4 * getopt_long(), or at least a common subset thereof:
6 * - Option reordering is not supported
7 * - -W foo is not supported
8 * - First optstring character "-" not supported.
17 int optind
, opterr
, optopt
;
18 static struct getopt_private_state
{
20 const char *last_optstring
;
21 char *const *last_argv
;
24 static inline const char *option_matches(const char *arg_str
,
27 while (*arg_str
!= '\0' && *arg_str
!= '=') {
28 if (*arg_str
++ != *opt_name
++)
38 int getopt_long(int argc
, char *const *argv
, const char *optstring
,
39 const struct option
*longopts
, int *longindex
)
45 /* getopt() relies on a number of different global state
46 variables, which can make this really confusing if there is
47 more than one use of getopt() in the same program. This
48 attempts to detect that situation by detecting if the
49 "optstring" or "argv" argument have changed since last time
50 we were called; if so, reinitialize the query state. */
52 if (optstring
!= pvt
.last_optstring
|| argv
!= pvt
.last_argv
||
53 optind
< 1 || optind
> argc
) {
54 /* optind doesn't match the current query */
55 pvt
.last_optstring
= optstring
;
63 /* First, eliminate all non-option cases */
65 if (!carg
|| carg
[0] != '-' || !carg
[1])
69 const struct option
*lo
;
70 const char *opt_end
= NULL
;
74 /* Either it's a long option, or it's -- */
80 for (lo
= longopts
; lo
->name
; lo
++) {
81 if ((opt_end
= option_matches(carg
+2, lo
->name
)))
88 *longindex
= lo
-longopts
;
90 if (*opt_end
== '=') {
92 optarg
= (char *)opt_end
+1;
95 } else if (lo
->has_arg
== 1) {
96 if (!(optarg
= argv
[optind
]))
109 if ((uintptr_t) (pvt
.optptr
- carg
) > (uintptr_t) strlen(carg
)) {
110 /* Someone frobbed optind, change to new opt. */
111 pvt
.optptr
= carg
+ 1;
116 if (opt
!= ':' && (osptr
= strchr(optstring
, opt
))) {
117 if (osptr
[1] == ':') {
119 /* Argument-taking option with attached
121 optarg
= (char *)pvt
.optptr
;
124 /* Argument-taking option with non-attached
126 if (argv
[optind
+ 1]) {
127 optarg
= (char *)argv
[optind
+1];
130 /* Missing argument */
132 return (optstring
[0] == ':')
138 /* Non-argument-taking option */
139 /* pvt.optptr will remember the exact position to