检查布尔值是否在混合 C/C++ 中定义

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

本文关键字:C++ 定义 混合 布尔值 是否 检查      更新时间:2023-10-16

所以我继承的一些代码遇到了问题。 这段代码在仅 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 */
}

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

如果我将#include "problem.h"包装在 extern "C" { ... } 中,我会收到同样的错误(我不明白,因为在编译为 C 时不应该有关键字bool

我尝试将块从#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来定义变量时,它什么也找不到。

任何帮助将不胜感激。

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

你可以用你的代码包围你的代码

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

您可以使用 C99 的bool

#ifndef __cplusplus
#include <stdbool.h>
#endif
bool myBoolean; // bool is declared as either C99's _Bool, or C++'s bool data type.

为什么要使用它?

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

您应该使用 __cplusplus 宏:

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

查看此链接,了解更多详细信息,了解C++常见问题解答。

我在 VS 中也有这个"'char'后跟'bool'是非法的"问题。对我来说,问题是我没有用分号结束我的类声明 - 我没想到这是问题所在,因为这在头文件中,并且问题出现在 cpp 文件中!例如:

class myClass
{
}; // <-- put the semi colon !!