Home > Blockchain >  Getting conflicting types error when trying to include a file
Getting conflicting types error when trying to include a file

Time:07-28

I have the following files (for example, this isn't my real project): file1.h:

typedef struct TestStruct{
    int a;
    int b;
} testStruct;
int doSomething();

file2.h:

#include "file1.h"
void doAnotherThing(testStruct a);

file3.h:

#include "file1.h"
void anotherFunction(testStruct a);

The .c files don't matter in this case. Now, I have a file called file4.c, which includes both file2 and file3. This gives off the following error:

file1.h:1:16: error: redefinition of ‘struct TestStruct’
 typedef struct TestStruct{
                ^
In file included from file3.c:1:0:
file1.h:1:16: note: originally defined here
 typedef struct TestStruct{
                ^
In file included from file3.h:1:0,
                 from file3.c:2:
file1.h:4:3: error: conflicting types for ‘testStruct’
 } testStruct;
   ^
In file included from file3.c:1:0:
file1.h:4:3: note: previous declaration of ‘testStruct’ was here
 } testStruct;

Which, as far as I understand it, is caused by both file2 and file3 including the same file. What way do I have of fixing this issue?

CodePudding user response:

You need to add include guards to file1.h to make sure its contents don't get included twice:

#ifndef FILE1_H
#define FILE1_H

typedef struct TestStruct{
    int a;
    int b;
} testStruct;
int doSomething();

#endif
  • Related