【发布时间】:2019-12-23 22:42:29
【问题描述】:
我正在尝试修改 getopt_long 手册页中的示例,以便它使用结构的标志成员。 但是我无法通过编译器抱怨我初始化标志变量的方式。 我只从手册页中的代码更改了一行,见下文,但是当我尝试编译时,我得到:
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 */
【问题讨论】:
-
StackOverflow 似乎对格式过于挑剔。在上面的帖子中,我将代码作为带有 ctl+K 的代码,并将文本重新编译,并将错误消息作为块引用。所以在我将块引用格式化为代码之前,我不会让我发布问题。 (事实并非如此)此外,他们没有告诉我他们反对帖子的哪一部分。我不得不将问题的各个部分随机格式化为代码,直到最终接受了问题。 pgmer6809
标签: c long-integer getopt