c - 在 c 中的 header 中使用枚举

标签 c struct enums header incomplete-type

我在尝试在 c 中的 header 内使用枚举时遇到了一些麻烦。这是我的代码的样子

主.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "listaEstatica.h"

int main(int argc, char** argv) {
    CACHORRO Tobias;
    strcpy(Tobias.nome, "Tobias");
    Tobias.registro = 123456789;
    Tobias.idade = 6;
    inserir(Tobias);

    exibirCachorro(cachorros[0]);

    return (EXIT_SUCCESS);
}

listaEstatica.c

#include "listaEstatica.h"

fim = 0;

enum Porte { Pequeno, Medio, Grande };
enum Estado { Machucado, Doente, DoencaInfeccosa};

int vazia() {
    if (fim == 0) {
        return 1;
    }
    return 0;
}

void inserir(CACHORRO cachorro) {
    if (fim == MAX) {
        printf("Não inseriu %s, lista cheia\n", cachorro.nome);
    } else {
        cachorros[fim] = cachorro;
        fim++;
        printf("Inserido %s OK\n", cachorro.nome);
    }
}

void exibirCachorro(CACHORRO cachorro) {
    printf("Nome: %s\n", cachorro.nome);
    printf("Registro: %i\n", cachorro.registro);
    printf("Idade: %i\n", cachorro.idade);
}

listaEstatica.h

typedef struct {
    char nome[30];
    int registro;
    int idade;
    enum Porte porte;
    enum Estado estado;
} CACHORRO;

int fim;
#define MAX 3
CACHORRO cachorros[MAX];

int vazia();

void inserir(CACHORRO cachorro);

void exibirCachorro(CACHORRO cachorro);

尝试编译这个游戏时出现以下错误

 listaEstatica.h:5:16: error: field ‘porte’ has incomplete type
     enum Porte porte;
            ^
 listaEstatica.h:6:17: error: field ‘estado’ has incomplete type
     enum Estado estado;

提前致谢,欢迎任何帮助

最佳答案

问题是,由于代码的顺序,您正在使用编译器尚不知道的枚举。

include 只是将头文件的内容复制到.c 文件中。因此,在您的情况下,您拥有这两个枚举的结构定义,并且定义了枚举的几行。因此,对于编译器而言,枚举在到达结构时并不存在。

将枚举移动到头文件和结构定义之前。

关于c - 在 c 中的 header 中使用枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31092534/

相关文章:

c++ - 从文本文件中读取创建的结构类型时遇到问题

c# - 结构尺寸

java - 使用外部枚举定义从 JAX-RS 端点生成 Swagger

c# - 将 int 转换为枚举的正确方法

c - setsocketoptions L2CAP_OPTIONS 失败并显示 "Invalid argument error"

CUDA 设备内存复制 : cudaMemcpyDeviceToDevice vs copy kernel

c - 重定向 C 内存泄漏中的指针

c - Ruby C 扩展 vs Spawn Executable via #system

c - 试图对结构中的数据进行排序,它排序正确但最后一行是错误的

java - 枚举 : get the keys list