If you use the GNU C library's implementation of getopt, then it will work like all GNU utilities do, because almost all of them use it. In particular, (quoting from man 3 getopt
):
By default, getopt() permutes the contents of argv as it scans, so that eventually all the nonoptions are at the end.
That's not quite the same as gcc
. gcc
cares about the relative order of optional and positional arguments. (For example, it makes a difference where -l
goes in the command line.) To do that, you'll have to tell GNU getopt
to not permute the arguments. Then, every time getopt
reports that it's done, optind
will have the index of the next positional argument (if any). You can then use that argument, increment optind
, and continue using getopt
, which will continue at the next argument.