multiple header files redefinition error in C

14k views Asked by At

When including multiple header files

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "stackADT.h"
#include "queueADT.h"

redefinition error occurs

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.

I tried attaching these, but it didn't work.

#ifndef _STACK_H_
#define _STACK_H_
....content....
#endif

Maybe it is only for C++.

Added relevant header file parts.

First 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;

and this is 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;
1

There are 1 answers

5
Eregrith On BEST ANSWER

You can't redefine the same symbol in two different header files and include them together, you will have the redefinition of 'xxx' error you can see.

What you can do about that is either remove the typedef struct node from one of the files, or even better, move your struct node definition in another file, have that file protected from multiple inclusion using #ifndefs as you said, and include it in both "stackADT.h" and "queueADT.h"

For example :

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 "..."

This way your .c source file can remain unchanged.