gpt4 book ai didi

c - getopt 中的 opterr 声明

转载 作者:太空宇宙 更新时间:2023-11-04 01:49:23 25 4
gpt4 key购买 nike

以下是来自 http://www.gnu.org 的示例代码.正如你们大多数人肯定会看到的那样,它是 getopt,我对变量声明有疑问。为什么

前面没有写什么type什么的
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;
}

最佳答案

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

extern int optind, opterr, optopt;

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

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

If getopt() does not recognize an option character, it prints an error message to stderr, stores the character in optopt, and returns '?'. The calling program may prevent the error message by setting opterr to 0.

关于c - getopt 中的 opterr 声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47069535/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com