3

I trying to emulate main() function like behavior for normal functions using string tokenizing and storing tokens in a NULL terminated char* array.

Every thing is fine except getopt(). It won't rearrange argv[0] coz it expects the first argument to be program name. But for my function the argv[0] isn't the program name. I want to make getopt() to also rearrange argv[0](non-option). How do I do that?

tez
  • 4,990
  • 12
  • 47
  • 67

3 Answers3

3

getopt(3) uses a global variable optind (option index) to track its progress through argv and initializes it to 1. Try setting optind = 0 before reading the options.

chrylis -cautiouslyoptimistic-
  • 75,269
  • 21
  • 115
  • 152
0

Try using

c = getopt(argc + 1, argv - 1, "xyz")

Edit: Which, as pointed out below, is a hack But I'd be interested to see a machine on which it didn't work.

Tom Tanner
  • 9,244
  • 3
  • 33
  • 61
  • I tend to say that `argv - 1`provokes undefined behaviour. So I' d consider this solution a dirty and unportable hack. – alk Aug 12 '13 at 10:45
  • only if you access it. I doubt that getopt does, – Tom Tanner Aug 12 '13 at 10:51
  • 1
    @TomTanner Technically I believe you're wrong. The standard says that a pointer addition or subtraction which gives a result outside the array bounds is undefined behaviour even if you subsequently do nothing with it, except for the special case of one past the end. In practise it's likely to work most places, but by the letter of the standard it's UB. – Nigel Harper Aug 12 '13 at 12:28
  • @TomTanner: I doubt this. Please have look at the answers to this question: http://stackoverflow.com/q/18186987/694576 – alk Aug 12 '13 at 12:59
0

Though the hack @Tom Tanner suggested worked for certain systems, it didn't compile for the target which I'm supposed to make it work. Another work around I found is to replace the first argument in my argv[] array with a dummy string and use getopt() with it.

tez
  • 4,990
  • 12
  • 47
  • 67