【问题标题】:opterr declaration in getoptgetopt 中的 opterr 声明
【发布时间】:2017-11-02 15:13:59
【问题描述】:

以下是来自http://www.gnu.org 的示例代码。大多数人肯定会看到,它是 getopt,我对变量声明有疑问。为什么前面没有类型或任何东西

opterr = 0;

我以前从未见过。

#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int
main (int argc, char **argv)
{
  int aflag = 0;
  int bflag = 0;
  char *cvalue = NULL;
  int index;
  int c;

  opterr = 0;


  while ((c = getopt (argc, argv, "abc:")) != -1)
    switch (c)
      {
      case 'a':
        aflag = 1;
        break;
      case 'b':
        bflag = 1;
        break;
      case 'c':
        cvalue = optarg;
        break;
      case '?':
        if (optopt == 'c')
          fprintf (stderr, "Option -%c requires an argument.\n", optopt);
        else if (isprint (optopt))
          fprintf (stderr, "Unknown option `-%c'.\n", optopt);
        else
          fprintf (stderr,
                   "Unknown option character `\\x%x'.\n",
                   optopt);
        return 1;
      default:
        abort ();
      }
  printf ("aflag = %d, bflag = %d, cvalue = %s\n",
          aflag, bflag, cvalue);

  for (index = optind; index < argc; index++)
    printf ("Non-option argument %s\n", argv[index]);
  return 0;
}

【问题讨论】:

  • 有趣的是你不问optarg来自哪里。
  • 您选择的 IDE 可能支持“显示声明”功能(或类似功能)。例如在 Eclipse CDT 中它是“F3”按钮,或者您可以右键单击变量并手动选择此函数。
  • @user0042 - :D 是的...还没想过这个问题

标签: c getopt


【解决方案1】:

opterr(3)unistd.h 中被声明为外部变量:

extern int optind, opterr, optopt;

所以它是一个在不同翻译单元中定义的全局变量,在本例中是您的标准 C 库。

设置为0的原因在manpage中也有说明:

如果getopt() 不能识别选项字符,它会向stderr 打印一条错误消息,将该字符存储在optopt 中,然后返回'?'。调用程序可以通过将opterr 设置为0 来阻止错误消息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-01
    相关资源
    最近更新 更多