检查bool是否在混合C/C++中定义

pre*_*lic 12 c c++

所以我遇到了一些我继承的代码问题.这个代码在仅限C的环境中正常构建,但现在我需要使用C++来调用此代码.标题problem.h包含:

#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 */
}
Run Code Online (Sandbox Code Playgroud)

当我将其编译为C++代码时,我得到了 error C2632: 'char' followed by 'bool' is illegal

如果我包装#include "problem.h"in extern "C" { ... }(我不明白,因为bool编译为C时应该没有关键字,我得到同样的错误?)

我试图消除块#ifndef _BOOL#endif,并编译为C++,和我得到的错误:

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

我只是不明白C++编译器是如何抱怨重新定义的bool,但是当我删除重新定义并尝试仅用于bool定义变量时,它找不到任何东西.

任何帮助是极大的赞赏.

Luc*_*ore 19

因为bool是C++中的基本类型(但不是C语言),并且无法重新定义.

你可以用你的代码包围

#ifndef __cplusplus
typedef unsigned char bool;
static const bool False = 0;
static const bool True = 1;
#endif
Run Code Online (Sandbox Code Playgroud)


Ric*_*III 7

您可以使用 C99 的bool

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

bool myBoolean; // bool is declared as either C99's _Bool, or C++'s bool data type.
Run Code Online (Sandbox Code Playgroud)

为什么要使用这个?

与其他 C99 代码兼容。_Bool常用在C99代码中,非常有用。它还使您能够拥有布尔数据类型而无需 typedef 很多东西,因为在幕后,_Bool是由编译器定义的数据类型。