包含多个头文件时
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "stackADT.h"
#include "queueADT.h"
发生重定义错误
In file included from graphTraverse3.c:10:
./queueADT.h:10:16: error: redefinition of 'node'
typedef struct node
^
./stackADT.h:9:16: note: previous definition is here
typedef struct node
^
In file included from graphTraverse3.c:10:
./queueADT.h:69:20: warning: incompatible pointer types assigning to
'QUEUE_NODE *' from 'struct node *' [-Wincompatible-pointer-types]
...queue->front = queue->front->next;
^ ~~~~~~~~~~~~~~~~~~
./queueADT.h:93:16: warning: incompatible pointer types assigning to
'QUEUE_NODE *' from 'struct node *' [-Wincompatible-pointer-types]
queue->front = queue->front->next;
^ ~~~~~~~~~~~~~~~~~~
./queueADT.h:117:23: warning: incompatible pointer types assigning to
'struct node *' from 'QUEUE_NODE *' [-Wincompatible-pointer-types]
queue->rear->next = newPtr;
^ ~~~~~~
3 warnings and 1 error generated.
我尝试附加这些,但没有成功。
#ifndef _STACK_H_
#define _STACK_H_
....content....
#endif
也许它只适用于 C++。
添加了相关头文件部分。
第一个队列ADT.h
#ifndef _QUEUE_H_
#define _QUEUE_H_
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
// data type
typedef struct node
{
void* dataPtr;
struct node* next;
} QUEUE_NODE;
这是 stackADT.h。
#ifndef _STACK_H_
#define _STACK_H_
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
// Structure Declarations
typedef struct nodeS
{
void* dataPtr;
struct nodeS* link;
} STACK_NODE;
最佳答案
您不能在两个不同的头文件中重新定义相同的符号并将它们包含在一起,您将看到 redefinition of 'xxx'
错误。
您可以做的就是从其中一个文件中删除 typedef struct node
,或者更好的是,将您的 struct node
定义移动到另一个文件中,正如您所说,该文件使用 #ifndef
进行了多重包含保护,并将其包含在“stackADT.h”和“queueADT.h”中
例如:
myNode.h:
#ifndef MYNODE_H_
# define MYNODE_H_
typedef struct node
{
char n;
int i;
} QUEUE_NODE;
#endif
stackADT.h:
#include <...>
#include "myNode.h"
#include "..."
队列ADT.h:
#include <...>
#include "myNode.h"
#include "..."
这样您的.c
源文件就可以保持不变。
关于c - C中多个头文件重定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30798444/