Reputation: 105
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 -
#ifndef A_H
#define A_H
typedef int INT;
// other variables and function definition
#endif
#ifndef B_H
#define B_H
typedef int INT;
// other variables and function definition
#endif
#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 ?
Upvotes: 2
Views: 4843
Reputation: 42012
If you are allowed to change the library code or compiler options then Michael Walz's answer is the way to go
In the unfortunate case that it's not changeable then it can be worked around by renaming before including the header then undefine it
#define INT INT_A
#include "a.h"
#undef INT
#define INT INT_B
#include "b.h"
#undef INT
Now just use INT_A
for all the interfaces in a.h
instead of INT
. Same to INT_B
in b.h
Upvotes: 1
Reputation: 50912
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;
}
Upvotes: 9