我正在一个有4个文件的项目中:main.c list.c hash.c structs.c和相应的.h文件。 问题是在list.c中,我需要链接structs.h。 这给我一个错误,说structs.c中的函数与structs.h文件中的该函数的声明冲突。
在lists.h中,我执行#include“ structs.h;在lists.c中,我执行#include” lists.h“ 而且我没有任何错误。 在stucts.c中,我#include“ structs.h”
lists.h:
#include "structs.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct list{
Instr head;
struct list *tail;
} *ILIST;
ILIST mkList(Instr, ILIST);
lists.c:
#include "lists.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
ILIST mkList(Instr n, ILIST l1) {
ILIST l = malloc(sizeof(struct list));
l->head = n;
l->tail = l1;
return l;
}
structs.h:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef enum {START, QUIT, ATRIB, ADD, SUB, MUL, PRINT, READ, IF, GOTO, LABEL} OpKind;
typedef enum {INT_CONST, STRING, EMPTY} ElemKind;
typedef struct{
ElemKind kind;
union
{
int val;
char* name;
}content;
} Elem;
structs.c:
#include "structs.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
我得到这样的错误
In file included from lists.h:1:0,
from main.c:3:
structs.h:5:16: error: redeclaration of enumerator ‘START’
typedef enum {START, QUIT, ATRIB, ADD, SUB, MUL, PRINT, READ, IF, GOTO, LABEL} OpKind;
^~~~~
In file included from main.c:1:0:
structs.h:5:16: note: previous definition of ‘START’ was here
typedef enum {START, QUIT, ATRIB, ADD, SUB, MUL, PRINT, READ, IF, GOTO, LABEL} OpKind;
^~~~~
答案 0 :(得分:4)
只包括标题防护,例如:
#ifndef __GUARD_STRUCTS__
#define__GUARD_STRUCTS__
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef enum {START, QUIT, ATRIB, ADD, SUB, MUL, PRINT, READ, IF, GOTO, LABEL} OpKind;
typedef enum {INT_CONST, STRING, EMPTY} ElemKind;
typedef struct{
ElemKind kind;
union
{
int val;
char* name;
}content;
} Elem;
#endif