View Full Version : Problem with "getopt" in Linux (GCC)

12-10-2011, 11:18 PM
Hi all,

I have this little snippet of test code:

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <getopt.h>

int main (int argc, char **argv)
int c, w, aflag, bflag, cflag;
c = w = aflag = bflag = cflag = 0;

opterr = 0;

while ((c = getopt (argc, argv, "abc")) != -1) {

w++; /* debug count how many times we go through */

switch (c) {

case 'a':
aflag = 1;
case 'b':
bflag = 1;
case 'c':
cflag = 1;
case '?':
fprintf(stdout, "Help shown here\n");
return 1;
fprintf(stdout, "Default: Should not see\n");
return 1;

fprintf(stdout, "While loop count = %d\n", w);

for (c = 0; c < argc; c++) {
fprintf(stdout, "argv[%d] = %s\n", c, argv[c]);
return 0;
Note the line in red... setting "opterr" to zero is supposed to suppress the built in error messages from getopt, yet it does not.

Running the code with an invalid option SHOULD simply print the help line, yet I get this:

root@michael:~/c-progs# ./getopt -x
./getopt: invalid option -- 'x'
Help shown here

The line in red isn't supposed to display.

I tried setting "opterr" to 1, -1 and leaving it out... no difference. What the heck? Anyone know?


-- Roger