1

I am writing a simple program to have -d with a parameter along with the other arguments

I want them run with aa.cc with the following options

  • aa -d 123 param1 param2 or
  • aa param1 param2 -d 123

I have written the code in the following way

    /* sample */

    char *level:
    while ((ch = getopt(argc, argv, "d:")) != EOF) {
        switch(ch) {
        case 'd':
            level = optarg;    
            debug = TRUE;
            break;
        default:
            usage();
            /*NOTREACHED*/
        }
    }

It is working fine when given as aa -d 123 param1 param2 but not when given as aa param1 param2 -d 123.

Can anyone please suggest how we can achieve that?

1
  • Note that getopt() is documented to return -1 rather than EOF after the last option is processed. The POSIX standard header for getopt() is <unistd.h> and that does not define EOF, so the definition of getopt() was changed (quite a while ago now) to decouple it from the <stdio.h> header. Commented Dec 22, 2011 at 6:11

1 Answer 1

2

Unless you're using the GNU version of getopt(), option arguments (such as -d 123) must precede non-option arguments (such as param1 and param2). (See POSIX 'Utility Conventions'.)

If you're using GNU getopt(), it will scan the entire argument list (up to but not including a -- argument), processing options found after non-options, unless the POSIXLY_CORRECT environment variable is set (in which case it behaves like POSIX getopt(), of course).

If you're not using GNU getopt(), you have to live with options before non-options, or switch to GNU getopt(), or write your own.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.