C中多个头文件重定义错误

multiple header files redefinition error in C

包含多个头文件时

#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++。

添加了相关的头文件部分。

第一个queueADT.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 "..."

queueADT.h:

#include <...>
#include "myNode.h"
#include "..."

这样您的 .c 源文件可以保持不变。