Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I avoid redefinition of types while including multiple header files?

I'm working on recompiling a C project and I'm not sure how do I fix this problem in a right way. Here is a situation -

a.h

#ifndef A_H
#define A_H
typedef int INT; 
// other variables and function definition
#endif

b.h

#ifndef B_H
#define B_H
typedef int INT;
// other variables and function definition
#endif

main.c

#include "a.h" 
#include "b.h"

int main()
{
    INT i = 10; 
    return 0;
}

The error I get in Linux with gcc:

In file included from ./main.c,

    ./b.h:<linenumber>: error: redefinition of typedef ‘INT’
    a.h.h:<linenumber>: note: previous declaration of ‘INT’ was here

I have to include both headers due to other variables and functions. I haven't written this code, but this seems to compile in my Solaris environment which is strange. What can I do to fix this ?

like image 938
SwapnilShivhare Avatar asked Jan 25 '26 10:01

SwapnilShivhare


1 Answers

Probably the native compiler on Solaris accepts that you can redefine a typedef (probably provided that the new typedef is identical to the previous one which is the case here).

I'd introduce another header file mytypes.h like this:

mytypes.h

#ifndef MYTYPES_H
#define MYTYPES_H
typedef int INT;     
#endif

Include mtypes.h whereever INT is used, possibly even in main.c:

a.h

#ifndef A_H
#define A_H
#include "mytypes.h"   // can be removed if INT is not used in a.h
// other variables and function definition
#endif

b.h

#ifndef B_H
#define B_H
#include "mytypes.h"   // can be removed if INT is not used in b.h
// other variables and function definition
#endif

main.c

#include "a.h" 
#include "b.h"
#include "mytypes.h"  // not really necessary because it's already included
                      // via a.h and b.h, but still good practice

int main()
{
    INT i = 10; 
    return 0;
}
like image 127
Jabberwocky Avatar answered Jan 26 '26 23:01

Jabberwocky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!