检查布尔值是否在混合 C/C++ 中定义
Check if bool is defined in mixed 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 */
}
当我将其编译为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 !!
- 在提升multi_index容器中,是否定义了"default index"?
- #定义c-预处理器常量..我做错了什么
- 用C++中的一个变量定义一个常量
- 部分定义/别名模板模板参数
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- #为""定义宏;静态";针对不同的上下文
- 如何确保C++函数在定义之前声明(如override关键字)
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 当类在C++中定义时,有什么方法可以"register"类吗?
- 在命名空间中定义函数还是限定函数
- 此代码是否违反一个定义规则
- 编译C++时未定义的引用
- 不同翻译单元中不可重载的非内联函数定义
- 为什么在定义函数之前先声明它
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 在类定义之后定义一个私有方法
- 使用用户定义函数的字符串反转
- 用户定义函数中的指针和输入
- vscode g++链路故障:体系结构x86_64的未定义符号
- 如何定义一个纯抽象基类