【问题标题】:getopt_long using flag struct membergetopt_long 使用标志结构成员
【发布时间】: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


【解决方案1】:

long_options 被声明为static。这意味着变量的初始化需要是一个常量表达式,编译器需要能够在编译时“计算”它。而int verbose是进入main函数时会创建的变量,变量的地址&amp;verbose在编译时是未知的。

您可以执行以下操作之一:

  • 从long_options 定义中删除static 关键字。
  • 将verbose 变量定义移动到文件范围。
  • 将static 关键字添加到变量verbose。

如您所见,in the documentation for getopt_longverbose_flag 变量在文件范围内声明并使用static。因此,&amp;verbose_flag 是一个常量表达式,可以用于其他static 变量的初始化。

有关更多信息,我建议您阅读constant expressions 和storage durations。

【讨论】:

  • 非常感谢您的快速回复。您对静态效果的解释甚至比您给我的链接中的解释还要好。把 static int verbose 去掉当然可以消除编译错误。再次感谢。
猜你喜欢
  • 1970-01-01
  • 2018-08-14
  • 2011-04-10
  • 2019-04-15
  • 2021-10-12
  • 1970-01-01
  • 1970-01-01
  • 2011-08-29
  • 1970-01-01
相关资源
最近更新 更多