Error about the Redefinition of a struct and conflicting types for a function

45 Views Asked by At

I have a given header (given1.h) file that includes my function prototypes, definitions, a struct definition, and libraries. I wanted to add a helper file called helper.h that incldues a function prototype called int readDataFile(char fileName[30], struct Animal testData[NUM_TEST_DATA]);

It would seem wise to add the prototype to given1.h but I must create a helper.h. Since the function prototype has struct Animal from given1.h and NUM_TEST-DATA, I need to add #include "given1.h", then include this both headers in both my main and function definition file. Only problem is that when I do this, I get an error saying

error: redefinition of ‘struct Animal’
   31 | struct Animal {
      |        ^~~~~~
given1.h:31:8: note: originally defined here
   31 | struct Animal {
      |        ^~~~~~
given1.h:40:5: error: conflicting types for ‘readFromFile’; have ‘int(char *, struct Animal *)’
   40 | int readFromFile (char fName [30], struct Animal dataZoo [NUM_SAMPLES]) ;
      |     ^~~~~~~~~~~~
givenA1.h:40:5: note: previous declaration of ‘readFromFile’ with type ‘int(char *, struct Animal *)’
   40 | int readFromFile (char fName [30], struct Animal dataZoo [NUM_SAMPLES]) ;

and so on for all my functions. What can I do to fix this?

I did try putting my prototype within givenA1 and it gave me an implicit differentiation warning and still even then, it must go in helper.h. For some reason, the program only runs without warnings/errors when I put the prototype in main. I have zero idea as to why it only runs when the prototype is in main. How can I declare this prototype with the correct parameters from given1.h without causing an error regarding a redefintion of struct and an error regarding conflicting types for all functions. I also use a make file to compile it.

1

There are 1 best solutions below

2
dbush On

The struct redefinition errors are appearing because you're including given1.h in multiple places in a single translation unit (i.e. a source file, the headers it includes, the headers those include, etc) resulting in the struct definition appearing in multiple places.

You can fix this by adding header guards in your header files. This prevents the contents from being included multiple times. For example:

given1.h:

#ifndef GIVEN_H
#define GIVEN_H

struct Animal {
   ...

int readFromFile (char fName [30], struct Animal dataZoo [NUM_SAMPLES]) ;

...

#endif