我目前正在用 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: %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;
}
如果我在 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 以一致的方式表现?