【问题标题】:GCC Error struct flexible array member with no named members没有命名成员的 GCC 错误结构灵活数组成员
【发布时间】:2017-12-11 16:38:24
【问题描述】:

opts.h:

#ifndef PINF_OPTS_H
#define PINF_OPTS_H
#endif //PINF_OPTS_H

// == DEFINE ==
#define MAX_OPTS 100

// == VAR ==
struct _opt {
    char *option; // e.g. --group
    char *alias; // e.g. -G
    int reqArg; // Require Argument | 0: No 1: Yes
    int maxArgs; // -1: Undefined/ Unlimited
    int func; /* Run Function? 0: No 1: Yes
               * If No, it can be checked with function 'isOptEnabled'
               */
} opt;

struct _optL {
    struct opt avOpt[MAX_OPTS];
} optL;

struct _acOpt {
    struct opt *acOpt[MAX_OPTS];
} acOpt;

// == FUNC ==
void initOpts(void);

opts.c:

#include "opts.h"

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

// == VAR ==
static struct optL *optList;
static struct acOpt *activeOpts;

// == CODE ==
void initOpt(void) {
    optList = (struct optL *)malloc(sizeof(struct optL *));
    activeOpts = (struct acOpt *)malloc(sizeof(struct acOpt *));
}

opts_test.c:

#include <stdio.h>
#include "../include/opts.h"

int main(void) {
    initOpts();
    return 0;
}

我编译它:

gcc -c 包含/opts.c && gcc -c opts_test.c && gcc -o opts_test opts_test.o opts.o; rm -f *.o;

输出:

In file included from include/opts.c:5:0:    
include/opts.h:14:16: error: array type has incomplete element type ‘struct opt’     
     struct opt avOpt[];     
                ^~~~~       
include/opts.h:28:17: error: flexible array member in a struct with no named members     
     struct opt *acOpt[];      
                 ^~~~~       

为什么 gcc 不编译我的文件?
在另一个项目中,我完全使用了这段代码并且它有效。
现在它不起作用....

【问题讨论】:

  • struct opt 使用时不知道。
  • 为什么标记为C++
  • 将 _optL 的定义移到 _opt 的定义之后。
  • 您的代码中没有struct opt 的定义。你只有一个struct _opt 的定义和一个名为opt 的对象。 struct optLstruct acOpt 有同样的问题。
  • @johnelemans 我试过了,但我不工作

标签: c gcc compiler-errors


【解决方案1】:

看起来您正在声明一个结构,然后尝试给它另一个名称。尝试使用 typedef,然后只使用没有“结构”的新名称。像这样。

此外,您分配的内存是指向结构的指针的大小,而不是结构的大小。

// == VAR ==
typedef struct _opt {
    char *option; // e.g. --group
    char *alias; // e.g. -G
    int reqArg; // Require Argument | 0: No 1: Yes
    int maxArgs; // -1: Undefined/ Unlimited
    int func; /* Run Function? 0: No 1: Yes
               * If No, it can be checked with function 'isOptEnabled'
               */
} opt_t;


typedef struct _optL {
   opt_t avOpt[MAX_OPTS];
} optL_t;

【讨论】:

  • 不,它不起作用。编译器错误:include/opts.h:24:8: error: 'struct' typdef struct _opt opt_t 之前的预期'='、','、';'、'asm' 或'attribute' ; ^~~~~~ 包括/opts.h:27:4: 错误:未知类型名称 ‘opt_t’ opt_t avOpt[MAX_OPTS]; ^~~~~
  • 它对我来说很好用。发布失败的确切行。
猜你喜欢
  • 1970-01-01
  • 2018-03-29
  • 1970-01-01
  • 2020-04-13
  • 2011-07-25
  • 2011-03-04
  • 2012-11-22
  • 2016-09-06
  • 2019-10-21
相关资源
最近更新 更多