Search code examples
cstructenumsheaderincomplete-type

Using enum inside header in c


i'm having a little bit of trouble trying to use enum inside header in c. Here's how my code look like

main.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);

Trying to compile this game me the following error

 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;

Thanks in advance, any help is welcome


Solution

  • The problem is, that you're using a enum that's not yet known to the compiler, due to the order of your code.

    An include literally just copies the contents of the header file into the .c file. So in your case you have your struct definition with these two enums and a few lines further down the enums are defined. So for the compiler the enums don't exist at the time it reaches the struct.

    Move the enums into the header file and before the struct definition.