I have code for bool typedef
typedef enum bool {
false,
true,
} bool;
in two headers files if it is not included in the ultimate parent header file, child C files cannot, of course, use type bool, though children of the lesser header file that also defines it can.
However if I define it in the ultimate parent header file then the lesser header file definition errors with “bool has already been declared in the current scope”
I need a solution for the lesser header where it may be included on a project that may or may not have already defined bool… What is the best way to do this??
Ta
First of all, if you’re working with a C99 compiler or later, there’s already a standard Boolean type defined in
stdbool.h.Secondly, you can usually avoid testing against
trueandfalsevalues directly, and I’ve found over the years that this actually leads to code that’s a little easier to read and less error-prone (that’s just a personal opinion, though — YMMV).The immediate solution is to surround your typedefs with an include guard:
This will keep the type from being declared more than once. However, as you’ve discovered, putting the same type definition in two different headers is a recipe for heartburn. It would be better to put the definition in its own header file (with the include guards as shown above), and then include that file where necessary.