C - 为什么getopt在linux上返回255?

jac*_*wah 6 c getopt

我最近一直在欺骗getopt(来自unistd.h).我编写了一些在使用MinGW的gcc编译的Windows 7下运行良好的代码,而不是在我的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;
}
Run Code Online (Sandbox Code Playgroud)

我得到的是,在未编程的8位算术中实际上255 -1,所以我试图在while条件中放置一个int转换,但是什么也没做.

Car*_*rum 11

看起来您的系统/工具链默认为无符号char类型.这意味着当getopt()返回-1时,它将转换为255并存储在其中t.然后将255提升为int类型(保持255)并进行比较-1,这是无法匹配的.

getopt()回报int,所以你应该申报tint匹配,但是如果你在使用设置char,你将需要使用signed char.

旁白:既然你说你正在使用gcc进行编译,那么-fsigned-char如果你想char在你的程序中对这个和其他变量进行签名,你也可能会发现这个标志很有用.

第二个:您可以通过传递-funsigned-char标志或更改tunsigned charWindows测试中的一个来复制失败,如果这样可以更容易调试.