Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if bool is defined in mixed C/C++

Tags:

c++

c

So I'm having issues with some code that I've inherited. This code was building fine in a C-only environment, but now I need to use C++ to call this code. The header problem.h contains:

#ifndef _BOOL
typedef unsigned char bool;
static const bool False = 0;
static const bool True = 1;
#endif

struct astruct
{
  bool myvar;
  /* and a bunch more */
}

When I compile it as C++ code, I get error C2632: 'char' followed by 'bool' is illegal

I get the same error if I wrap the #include "problem.h" in extern "C" { ... } (which I don't understand, because there should be no keyword bool when compiling as C?)

I tried removing the block from #ifndef _BOOL to #endif, and compiling as C++, and I get errors:

error C2061: C requires that a struct or union has at least one member
error C2061: syntax error: identifier 'bool'

I just don't understand how the C++ compiler is complaining about a redefinition of bool, yet when I remove the redefinition and try to just use bool to define variables, it doesn't find anything.

Any help is greatly appreciated.

like image 425
prelic Avatar asked May 17 '12 12:05

prelic


2 Answers

Because bool is a basic type in C++ (but not in C), and can't be redefined.

You can surround your code with

#ifndef __cplusplus
typedef unsigned char bool;
static const bool False = 0;
static const bool True = 1;
#endif
like image 131
Luchian Grigore Avatar answered Oct 25 '22 10:10

Luchian Grigore


You can use C99's bool:

#ifndef __cplusplus
#include <stdbool.h>
#endif

bool myBoolean; // bool is declared as either C99's _Bool, or C++'s bool data type.

Why should you use this?

For compatibility with other C99 code. _Bool is commonly used in C99 Code, and is very useful. It also grants you the ability to have a boolean datatype without the need to typedef a lot of stuff, as behind the scenes, _Bool is a datatype defined by the compiler.

like image 41
Richard J. Ross III Avatar answered Oct 25 '22 09:10

Richard J. Ross III