C-错误 : array type has incomplete element type in a extern struct declaration

标签 c struct extern

我有下一个代码:

// FILE: HEADERS.h
extern struct viaje viajes[];
extern struct cliente clientes[];

// FILE: STRUCTS.c
struct viaje {
    char identificador[30+1];
    char ciudadDestino[30+1];
    char hotel[30+1];
    int numeroNoches;
    char tipoTransporte[30+1];
    float precioAlojamiento;
    float precioDesplazamiento;
};

struct cliente {
    char dni[30+1];
    char nombre[30+1];
    char apellidos[30+1];
    char direccion[30+1];
    int totalViajes;
    struct viaje viajes[50];
} clientes[20];

当我尝试编译代码时出现下一个错误:error: array type has incomplete element type in a extern struct declaration 我不知道为什么会这样。我试过在 Structs 定义之后也包含 header ,但我没有收到任何错误,但这是错误的,正确的方法是定义 -> 声明,而不是声明 -> 定义。

为什么会这样?谢谢。

最佳答案

如果您定义或声明结构的实例,则需要首先定义该结构。否则,编译器无法确定结构的大小或其成员是什么。

您需要将结构体定义放在头文件中的 extern 声明之前:

struct viaje {
    char identificador[30+1];
    char ciudadDestino[30+1];
    char hotel[30+1];
    int numeroNoches;
    char tipoTransporte[30+1];
    float precioAlojamiento;
    float precioDesplazamiento;
};

struct cliente {
    char dni[30+1];
    char nombre[30+1];
    char apellidos[30+1];
    char direccion[30+1];
    int totalViajes;
    struct viaje viajes[50];
};   // note that there are no instances defined here

extern struct viaje viajes[];
extern struct cliente clientes[];

然后您的 .c 文件将包含实例:

// Changed size viajes from 20 to 50
struct viaje viajes[50];
struct cliente clientes[20];

关于C-错误 : array type has incomplete element type in a extern struct declaration,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49182184/

相关文章:

c - C 中的字符串动态分配

c++ - 在定义结构之前如何使用指向结构的指针?

c - 图像翻转不正确...为什么?

c++ - 使用许多外部类型声明时如何加快编译时间

c - 使用链接器命令将 C 中的数组分配到特定位置

c - `sudo` 从 C 以 root 权限连接到 wifi

c - 在 gcc 4.2.1 上,指向二维数组的指针的大小为 8 的原因是什么?

c - pipe2(...) vs pipe() + fcntl(...),为什么不同?

c - C 结构 malloc 代码中的 VC++ 2010 错误

c - extern 是可选的吗?