tags:

views:

106

answers:

3

I've written a collection of data structures and functions in C, some of which use the _Bool data type. When I began, the project was going to be pure C. Now I am investigating using a C++ based GUI tool kit and have made the backend code into a library.

However, when compiling the C++ GUI the following error is emitted by the compiler:

ISO C++ forbids declaration of '_Bool' with no type

I initially thought I could search & replace _Bool to bool and create:

/* mybool.h */
#ifndef MYBOOL_H
#define MYBOOL_H

typedef _Bool bool;

#endif /* MYBOOL_H */

and then in any headers that use _Bool

#ifdef __cplusplus
extern "C" {
#else
#include "mybool.h"
#endif

/* rest of header... */

Until I realized this would be compiling the library with one boolean (C _Bool) data type, and linking against the library using another (C++ bool). Practically, this might not matter, but theoretically, it probably does (there might be some obscure system somewhere which doing so like this causes the universe to turn inside out).

I suppose I could just use an int and use 0 for false and 1 for true, and typedef it with something like typedef int mybool, but it seems unattractive.

Is there a better/idiomatic/standard way to do this?

A: 

use typedef int _Bool for both your C and C++ code. I will be surprised if _Bool is defined as anything else.

doron
_Bool is the C99 native type.
James Morris
Thus you can't.
James Morris
A: 

Dumbass! Just #include <stdbool.h> and use bool.

James Morris
@James dumb ass : (adjective) extremely unintelligent. (Hyphenated. See "ass"). Do you mean that in contrast you are extremely more intelligent because you know that one should include #include <stdbool.h> to use bool in C. I dare not say what I think of your answer.
Stephane Rolland
Why yes, in contrast to my dumb-ass self, of course I am more intelligent.
James Morris
Accepted my own answer and my decision to call myself a dumb-ass (for not realizing the answer **before** asking the question on stackoverflow.com).
James Morris
+2  A: 

If the C and C++ compilers you are using are from the same vendor then I would expect the C _Bool to be the same type as C++ bool, and that including <stdbool.h> would make everything nicely interoperable. If they are from different vendors then you'll need to check for compatibility.

Note, you can always test the __cplusplus macro in your header to determine whether or not the code is being compiled as C++, and set the types appropriately.

Anthony Williams
I can always test the __cplusplus macro in my header... Mmmm yeah, well spotted.
James Morris