我正在尝试将手册页中的示例改编为getopt_long,以便它使用结构的标志成员。但是我无法避免编译器抱怨我初始化flags变量的方式。我只更改了手册页中的代码的一行,请参见下文,但是当我尝试编译时,得到:
gcc -Wall -c gnu_get_lopt.c
gnu_get_lopt.c: In function ‘main’:
gnu_get_lopt.c:20:51: error: initializer element is not constant
{"verbose", no_argument, &verbose, 9 },
^
gnu_get_lopt.c:20:51: note: (near initialization for ‘long_options[3].flag’)
这里的其他问题re getopt_long似乎可以使用此方法。我在做什么错?
pgmer6809
这是代码的开头:
#include <stdio.h> /* for printf */
#include <stdlib.h> /* for exit */
#include <getopt.h>
int main(int argc, char **argv) {
int c;
int digit_optind = 0;
int verbose;
while (1) {
int this_option_optind = optind ? optind : 1;
int option_index = 0;
static struct option long_options[] = {
/* Option, has_arg, flags, Val */
{"add", required_argument, 0, 0 },
{"append", optional_argument, 0, 0 },
{"delete", required_argument, 0, 0 },
/* {"verbose", no_argument, 0, 0 }, // Original GNU provided line. */
{"verbose", no_argument, &verbose, 9 }, /* changed line to use flag */
{"create", required_argument, 0, 'c'},
{"file", required_argument, 0, 0 },
{0, 0, 0, 0 }
};
c = getopt_long(argc, argv, "abc:d:012",
long_options, &option_index);
if (c == -1) // no more options
break; // break from while
<---- remaining program omitted for brevity ------>
} /* end main */
long_options
被声明为static
。这意味着变量的初始化需要为constant expression,编译器需要能够在编译时对其进行“计算”。但是int verbose
是将在进入主函数时创建的变量,该变量的地址&verbose
在编译时未知。
您可以执行以下一项操作:
static
定义中删除long_options
关键字。verbose
变量定义移动到文件范围。static
关键字添加到变量verbose
。您可以看到in the documentation for getopt_long,verbose_flag
变量是在文件范围内并使用static
声明的。因此,&verbose_flag
是一个常量表达式,可以在其他static
变量的初始化中使用。
有关更多信息,我建议您阅读有关constant expressions和storage durations的信息。