我最近一直在玩 getopt
(来自 unistd.h)。我编写了一些代码,在 Windows 7 下使用 MinGW 的 gcc 编译时运行良好,但在我的 Raspberry Pi 上的 Raspbian Linux 下不能工作(我使用 gcc 编译它们,没有选项;gcc t.c
)。出于某种原因,getopt 在没有开关时返回 int 255 或 char ÿ,而实际上它应该返回 -1。
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
char t;
opterr = 0;
while ((t = getopt(argc, argv, "a:")) != -1)
switch (t) {
case 'a':
printf("-a with argument %s\n", optarg);
return 0;
case '?':
printf("uknown option\n");
return 1;
default:
/* This is always 255 under linux, and is never reached under windows */
printf("getopt returned int %d (char %c)\n", t, t);
return 2;
}
return 0;
}
我的一个想法是,实际上 255 是 -1 在未签名的 8 位算术中,所以我试图在 while 条件中进行 int 转换,但那没有任何作用。
最佳答案
看起来您的系统/工具链默认为无符号 char
类型。这意味着当 getopt()
返回 -1 时,它会转换为 255 并存储在 t
中。然后 255 被提升为 int
类型(保持 255)并与永远无法匹配的 -1
进行比较。
getopt()
返回 int
,所以你真的应该将 t
声明为 int
来匹配,但是如果你准备使用 char
,你将需要使用 signed char
。
旁白:由于您说您正在使用 gcc 进行编译,如果您希望在您的变量中包含此变量和其他 char
变量,您可能还会发现 -fsigned-char
标志很有用要签名的程序。
第二个旁白:您可以通过传递 -funsigned-char
标志或将 t
更改为 unsigned char
来复制失败你的 Windows 测试,如果这使得它更容易调试。
关于C - 为什么 getopt 在 Linux 上返回 255?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17070958/