Pergunta

I have errors when compiling my project with codeblocks. My problem comes from a enum definition, and from a struct definition.

They are bot defined in a header file, that worked since i was only using those enum and struct in the .c associated file. But when i include the .h file in another .c file, i get errors, here is some code;

maps.h

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

enum Property { BACKGROUND, FOREGROUND, BLOCK, EVENT };

typedef struct {
   char map_name[50];
   int width;
   int height;
   char* map_struct;
}rpgMap;
char getTileProperty(rpgMap map, int x, int y, int property);

maps.c

#include "maps.h"

char getTileProperty(rpgMap map, int x, int y, int property){    // Works
   char value = NULL;
   value = map.map_struct[(((y*(map.width-1))+y+x) * 4 ) + property];
   return value;
}   
rpgMap loadMap(unsigned char* map){
   rpgMap Map;
       //....
       //some code
       //...
   return Map;
}
// This works until i include maps.h in another .c file

So here's the stuff, when i include maps.h in eg. game.c or game.h i have this error;

error: nested redefinition of 'enum Property'

I don't get it !

Foi útil?

Solução

You need to add header guards to your header files otherwise you will get multiple declarations.

For example, for your maps.h surround it with this:

#ifndef MAPS_H
#define MAPS_H

...


#endif

Outras dicas

Any source file that includes your header file will declare a single instance variable with the possible enumerated values of { BACKGROUND, FOREGROUND, BLOCK, EVENT }. I'm not sure that this is your intention. In general it is not good practice to do so.

If you intended to declare a type of enumeration and allow instances to be created elsewhere, put this in your header file:

typedef enum { BACKGROUND, FOREGROUND, BLOCK, EVENT } Property_t;

And then in your source files, declare the enumeration like so:

static Property_t property = BACKGROUND;

If you intended to create a variable that can be accessed from multiple source files then do put this in your header file:

typedef enum { BACKGROUND, FOREGROUND, BLOCK, EVENT } Property_t;
extern Property_t property;

and in a single source file, declare the variable:

Property_t property = BACKGROUND;
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top