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

标签 c header redefinition

包含多个头文件时

#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/

相关文章:

python-3.x - 要重新定义哪些 Python 对象比较方法以使 sorted() 工作?

objective-c - 在 Objective-C 中使用枚举名称作为值标识符

c - 如何链接多个 .c 文件

c - 迷你 shell 项目中的信号处理程序

c - 尝试在 C 中打印矩阵时对函数的 undefined reference

mysql - int argc MY_ATTRIBUTE((未使用)) 表示

php - 如何阻止 PHP 在文件开头添加 LF 前缀

rest - HTTP Allow header 应该包含 "OPTIONS"吗?

C++ 从 HTTP 响应中获取图片

gcc - 如何#define __forceinline 内联?