我在尝试在 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/