Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I mimic a C header that redefines bool in C++?

You can hack it!

The library, call it fooLib, thinks it's using some type bool which it has the prerogative to define. To the library, bool is just an identifier.

So, you can just force it to use another identifier instead:

#define bool fooLib_bool
#include "fooLib.h"
#undef bool
#undef true
#undef false

Now the compiler sees the offending line transformed to this:

typedef int fooLib_bool;

You're stuck with the interface using type fooLib_bool = int instead of a real bool, but that's impossible to work around, as the code might in fact rely on the properties of int, and library binary would have been compiled with such an assumption baked in.


I suppose you can wrap the offending code into a header and then undef what you don't need

Library_wrapper.h:

#define bool something_else // This will get you past the C++ compilation
#include "library.h"
#undef false
#undef true
#undef bool

main.cpp:

#include "Library_wrapper.h" 
#include "boost.h"

Regarding the typedef.. the compiler should complain if you try to redefine a basic type in C++. You can redeclare a type by the way (it is allowed in C++) or define it (simple text replacement).


Unfortunately, no, you cannot use this file in Standard C++:

§7.1.3 [dcl.typedef]

6/ In a given scope, a typedef specifier shall not be used to redefine the name of any type declared in that scope to refer to a different type.

Thus typedef ... bool; is forbidden.

§17.6.4.3.1 [macro.names]

2/ A translation unit shall not #define or #undef names lexically identical to keywords, to the identifiers listed in Table 3, or to the attribute-tokens described in 7.6.

And in §2.12 [lex.key] we find that bool is a keyword.

Thus trying to trick the compiler by using #define bool ... prior to including the offending file is forbidden.


So, what is the alternative ? A shim !

Isolate that offending library behind a C & C++ compatible header of your own; and compile this part as C. Then you can include your own header in the C++ program without issue or tricks.

Note: yes, most compilers will probably accept #define bool ..., but it is still explicitly forbidden by the Standard.


You may copy a bad header and use an edited copy. Tell to compiler the path it should prefer and...


You could compile the code which uses the header as C, then just link it together with your C++ object files. You probably use MSVC or GCC; both can compile code as either C++ or C, and will allow you to create compatible object files.

Whether that's a clean solution or unnecessary overkill really depends on the exact situation.