Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C typedef name conflict

Tags:

c

typedef

I have gotten 2 header files that I include that both have typedef of the same name.

Let's say aaa.h and bbb.h. They came from 2 unrelated 3rd party packages and I have no control of these 2 files but have to use them. I don't include both file directly but they are rather sub-included in the top level header file. (ie. I include a.h and b.h which respectively included them)

My program wont compile when they are both included because of the name conflict.

So my temporary solution is I copied aaa.h into my source tree with only the typedef removed, called myaaa.h. At the top of the file I keep the "#ifndef AAA_H, #define AAA_H" wrapper intact so when I include myaaa.h, aaa.h would not be included because the AAA_H flag is already defined, indirectly removed the typedef conflict.

Is there a cleverer way to do this without adding such file (and I have to version control it) to my source?

Thanks!

like image 220
kennyc Avatar asked Sep 05 '12 23:09

kennyc


1 Answers

#define conflicting_typedef aaa_conflicting_typedef
#include "aaa.h"
#undef  conflicting_typedef
#define conflicting_typedef bbb_conflicting_typedef
#include "bbb.h"
#undef  conflicting_typedef
#define conflicting_typedef ambiguous use aaa_conflicting_typedef or bbb_conflicting_typedef

If you need to refer to the typedef from aaa.h, you can use the name aaa_conflicting_typedef; to refer to the typedef from bbb.h, use the name bbb_conflicting_typedef. If (as is probably the case) you don't need to refer to either typedef in your code, then you're good to go. The final #define ensures that you don't use the plain name; you must use the correct mapped name.

Clearly, this should not be repeated; if there's more than one file that needs this stanza, you put it into your own header "aaa_bbb.h" and include that where you need the stanza. You can even detect whether either aaa.h or bbb.h has already been included and reject the compilation if it has (you can't detect if they're included after this, but the fact that they've been included once under your control means they should not be included again).

If this was C++, you'd have a bigger problem because of type-safe linkage. OTOH, the library vendors are then both guilty of improper name space control.

like image 127
Jonathan Leffler Avatar answered Nov 10 '22 09:11

Jonathan Leffler