Can someone help me with the getopt function?
When I do the following in main:
char *argv1[] = {\"testexec\",\"-?\"};
char *argv2[] = {\"testexec\",\
The getopt()
function uses some global variables, like optind
and optarg
, to store state information between calls. After you finish processing one set of options, there is data left in those variables that is causing problems with the next set of options. You could potentially try to reset getopt
's state between calls by clearing the variables, but I'm not sure that would work since the function might use other variables which aren't documented and you'd never know if you'd gotten them all; besides, it would be absolutely nonportable (i.e. if the implementation of getopt()
changes, your code breaks). See the man page for details. Best not to use getopt()
for more than one set of arguments in a given program if you can help it.
I'm not sure if there is an actual function to reset getopt
's state (or perhaps a reentrant version of the function, which lets you store the state in your own variables)... I seem to remember seeing something like that once, but I can't find it now that I look :-/