简体   繁体   English

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

[英]C - Why does getopt return 255 on linux?

I've been fooling around with getopt (from unistd.h) recently. 我最近一直在使用getopt (来自unistd.h)。 I wrote some code that worked fine under Windows 7 compiled with gcc from MinGW, while not working under Raspbian Linux on my Raspberry Pi (I compiled them both with gcc, no options; gcc tc ). 我写了一些在使用MinGW的gcc编译的Windows 7下运行良好的代码,而不是在我的Raspberry Pi上使用Raspbian Linux工作(我用gcc编译它们,没有选项; gcc tc )。 For some reason getopt returns int 255 or char ÿ when faced with no switches, when really it should return -1. 出于某种原因,当面对没有开关时,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;
}

One tought I had was that, actually 255 is -1 in unsinged 8-bit arithmetic, so I tried to put an int cast in the while conditional, but that did nothing. 我得到的是,在未编程的8位算术中实际上255 -1,所以我试图在while条件中放置一个int转换,但是什么也没做。

It looks like your system/toolchain defaults to an unsigned char type. 看起来您的系统/工具链默认为unsigned char类型。 That means when getopt() returns -1, it gets converted to 255 and stored in t . 这意味着当getopt()返回-1时,它将转换为255并存储在t Then that 255 gets promoted to int type (staying 255) and compared to -1 , which can't ever match. 然后将255提升为int类型(保持255)并与-1进行比较,这是无法匹配的。

getopt() returns int , so you should really declare t as int to match, but if you're set on using char , you're going to need to use signed char . getopt()返回int ,所以你应该把t声明为int来匹配,但如果你使用char设置,你将需要使用signed char

Aside: Since you say you're compiling with gcc, you might also find the -fsigned-char flag helpful if you want this and other char variables in your program to be signed. 旁白:既然你说你正在用gcc进行编译,你可能会发现-fsigned-char标志有用,如果你想要在你的程序中对这个和其他char变量进行签名。

Second Aside: You can duplicate the failure by passing the -funsigned-char flag or by changing t to be an unsigned char in your Windows test, if that makes it easier to debug. 第二个:您可以通过传递-funsigned-char标志或在Windows测试中将t更改为unsigned char来复制失败,如果这样可以更容易调试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM