DBPaul
DBPaul

Reputation: 580

How to allow non-option arguments in any order to getopt?

I have a C program which expects to be called with several options and 1 non-option argument (i.e. with no associated option letter), and uses getopt to parse these options. For example, it could be called with:

Example1: myProgram -a "aParam" -b "bParam" "xParam"

I have been using SLES10, and the options worked in any order. For example, the non-option argument, "xParam" could come first:

Example2: myProgram "xParam" -a "aParam" -b "bParam"

However, when testing in SLES11, it seems that getopt stops processing as soon as it reaches a non-option parameter, so example 2 above does not work.

I've read the getopt man pages and seen that this may be relevant:

If the first character of optstring is '+' or the environment variable POSIXLY_CORRECT is set, then option processing stops as soon as a nonoption argument is encountered.

I'm not sure if SLES11 sets POSIXLY_CORRECT by default. What is the best way to get the old SLES10 getopt behaviour in SLES11?

Upvotes: 4

Views: 1669

Answers (1)

DBPaul
DBPaul

Reputation: 580

It turns out that by default it was redirecting to _posix_getopt(), which was causing the behaviour I described above.

The possible solutions I found to this in the end:

  1. Use getopt_long() instead. This doesn't seem to have a posix equivalent.
  2. Define _GNU_SOURCE, which stops the redirection.
  3. Manually reorder the parameters, possibly using a wrapper shell script.

Upvotes: 1

Related Questions