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.
14 int optind
, opterr
, optopt
;
16 static struct getopt_private_state
{
18 const char *last_optstring
;
19 char *const *last_argv
;
22 static inline const char *option_matches(const char *arg_str
,
25 while (*arg_str
!= '\0' && *arg_str
!= '=') {
26 if (*arg_str
++ != *opt_name
++)
36 int getopt_long(int argc
, char *const *argv
, const char *optstring
,
37 const struct option
*longopts
, int *longindex
)
43 /* getopt() relies on a number of different global state
44 variables, which can make this really confusing if there is
45 more than one use of getopt() in the same program. This
46 attempts to detect that situation by detecting if the
47 "optstring" or "argv" argument have changed since last time
48 we were called; if so, reinitialize the query state. */
50 if (optstring
!= pvt
.last_optstring
|| argv
!= pvt
.last_argv
||
51 optind
< 1 || optind
> argc
) {
52 /* optind doesn't match the current query */
53 pvt
.last_optstring
= optstring
;
61 /* First, eliminate all non-option cases */
63 if (!carg
|| carg
[0] != '-' || !carg
[1])
67 const struct option
*lo
;
68 const char *opt_end
= NULL
;
72 /* Either it's a long option, or it's -- */
78 for (lo
= longopts
; lo
->name
; lo
++) {
79 if ((opt_end
= option_matches(carg
+2, lo
->name
)))
86 *longindex
= lo
-longopts
;
88 if (*opt_end
== '=') {
90 optarg
= (char *)opt_end
+1;
93 } else if (lo
->has_arg
== 1) {
94 if (!(optarg
= argv
[optind
]))
107 if ((uintptr_t) (pvt
.optptr
- carg
) > (uintptr_t) strlen(carg
)) {
108 /* Someone frobbed optind, change to new opt. */
109 pvt
.optptr
= carg
+ 1;
114 if (opt
!= ':' && (osptr
= strchr(optstring
, opt
))) {
115 if (osptr
[1] == ':') {
117 /* Argument-taking option with attached
119 optarg
= (char *)pvt
.optptr
;
122 /* Argument-taking option with non-attached
124 if (argv
[optind
+ 1]) {
125 optarg
= (char *)argv
[optind
+1];
128 /* Missing argument */
130 return (optstring
[0] == ':')
136 /* Non-argument-taking option */
137 /* pvt.optptr will remember the exact position to