Question

I compile the same code by gcc on OSX and CentOS:

while (( opt = getopt (argc, argv, "hp:" )) != -1 )
    {
        fprintf (stderr,"+++++++++++ %d\n\n", opt );
        switch ( opt )
            {
            case 'h':
                    fprintf(stderr, "Help Page \n %s", help_str);
                    return 1;

            case 'p':
                    filename = optarg ;
                    fprintf(stderr,"================== %s\n",optarg);
                    break;

            case '?':
                    printf("ZHZHZHZHZHUT\n");
                    return 3;

            default:
                break;
            }
    }

Then I try to run ./a.out -p ./file.txt ya.ru and ./a.out ya.ru -p ./file.txt On CentOS 6.5 both variants work.

But on MAC OS X(10.9) variant ./a.out ya.ru -p ./file.txt (free parameter before dependent parameter ) does not work. -p and /file.txt are used as simple arguments (not by getopt).

Full code is here

Thanks.

Was it helpful?

Solution

The documented behaviour of GNU getopt() is to stop at the first non-option argument only when in POSIX mode, which can be set via a + at the start of the option string or by setting the POSIXLY_CORRECT environment variable.

In its default mode, GNU getopt() 'permutes the contents of argv as it scans, so eventually all the non-options are at the end.'

You are hitting this difference in the behaviour — it is the difference between GNU getopt() and BSD getopt() behaviour, because the BSD getopt() has POSIX semantics.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top