Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting conflicting types error when trying to include a file

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading