开发者

getopt compatibility across platforms

开发者 https://www.devze.com 2023-02-21 21:01 出处:网络
I am currently writing a simple program in C, which can accept numeric command line arguments. But I also want it to have command line options. I\'ve noticed an inconsistency across different operatin

I am currently writing a simple program in C, which can accept numeric command line arguments. But I also want it to have command line options. I've noticed an inconsistency across different operating systems if one of the numeric arguments is negative (i.e. getopt sometimes does/sometimes doesn't confuse the -ve as an argument). For example:

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

int main(int argc, char* argv[])
{
  char ch;

  while ((ch = getopt(argc, argv, "d")) != -1) {
    switch (ch) {
    case 'd':
      /* Dummy option */
      break;
    default:
      printf("Unknown option: %c\n", ch);
      return 1;
    }
  }
  argc -= optind;
  argv += optind - 1;

  if (argc < 2) {
    fprintf(stderr, "Not enough arguments\n");
    return 1;
  }

  float f = atof(argv[1]);
  printf("f is %f\n", f);
  float g = atof(argv[2]);
  printf("g is %f\n", g);
  return 0;
}

If I compile and run this program on the Mac and under Cygwin开发者_如何转开发 I get the following behavior:

$ ./getopttest -d 1 -1
f is 1.000000
g is -1.000000

But if I try the same thing on Ubuntu and MingW on Windows I get this:

$ ./getopttest -d 1 -1
./getopttest: invalid option -- '1'
Unknown option: ?

Clearly it was a bit of a mistake having numeric arguments and options alongside each other - but is there a way of making getopt behave in a consistent manner?


Use -- to separate options from things that are not to be options.

$ ./getopttest -d -- 1 -1

will never try to read the -1 as an option.

0

精彩评论

暂无评论...
验证码 换一张
取 消