跨平台的getopt兼容性

我目前正在用C编写一个简单的程序,它可以接受数字命令行参数。但我也希望它有命令行选项。我注意到,如果其中一个数字参数为负数,则不同操作系统之间存在不一致性(即getopt有时会/有时不会将-ve作为参数混淆)。例如:
#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: %cn", ch);
      return 1;
    }
  }
  argc -= optind;
  argv += optind - 1;

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

  float f = atof(argv[1]);
  printf("f is %fn", f);
  float g = atof(argv[2]);
  printf("g is %fn", g);
  return 0;
}
如果我在Mac上和Cygwin下编译并运行该程序,我会得到以下行为:
$ ./getopttest -d 1 -1
f is 1.000000
g is -1.000000
但是,如果我在Windows上的Ubuntu和MingW上尝试相同的操作,我会得到:
$ ./getopttest -d 1 -1
./getopttest: invalid option -- '1'
Unknown option: ?
很明显,将数字参数和选项放在一起是有点错误的 - 但有没有办法让getopt以一致的方式运行?     
已邀请:
使用
--
将选项与不是选项的选项分开。
$ ./getopttest -d -- 1 -1
绝不会尝试将
-1
作为一种选择。     

要回复问题请先登录注册