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

所以我遇到了一些我inheritance的代码问题。 此代码在仅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

如果我在extern "C" { ... }包装#include "problem.h"我会得到同样的错误(我不明白,因为编译为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  #endif bool myBoolean; // bool is declared as either C99's _Bool, or C++'s bool data type. 

你为什么要用这个?

与其他C99代码兼容。 _Bool常用于C99代码,非常有用。 它还允许你具有布尔数据类型的能力,而不需要输入很多东西,因为在幕后, _Bool是由编译器定义的数据类型。

你应该使用__cplusplus宏:

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

有关更多详细信息,请查看此C ++ FAQ链接 。

在VS中我有这个“’char’后跟’bool’是非法的”问题。 对我来说问题是我没有用分号结束我的类声明 – 我不希望这是问题,因为这是在头文件中,问题出现在cpp文件中! 例如:

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