2

我正在将我在 CodeWarrior v5.2 中开发的应用程序迁移到使用 ARM C 编译器 v5.06 的 Keil uVision v5.25。

在我的代码中,我用来bool表示布尔值,它types.h在我的项目的文件中定义为:

typedef enum _bool 
{ 
  false = 0, 
  true = 1 
} bool;

当我尝试编译我的代码时,编译器会生成有关我将比较结果隐式分配给具有这种类型的变量的行的警告:

src\c\drivers\motor.c(168): warning:  #188-D: enumerated type mixed with another type
    const bool motorStopped = timeSinceLastEvent > maxPulseWidth;
src\c\drivers\motor.c(169): warning:  #188-D: enumerated type mixed with another type
    const bool motorStalled = motorStopped && isMotorDriven();

我理解为什么会产生这些警告。我知道我可以通过显式转换为来抑制这些警告bool,例如:

const bool motorStopped = (bool)(timeSinceLastEvent > maxPulseWidth);

但是,对每个布尔条件都这样做是非常难看的。我想知道是否有一种方法可以将 Keil uVision / ARM 编译器(或修改我的代码)配置为不生成关于 的警告bool,而不会完全禁用有关将枚举类型与其他类型混合的警告。

这些是我可用于配置编译器的选项:

4

2 回答 2

1

感觉很脏,但我通过修改types.hSDK 工具包附带的文件来解决这个问题,使其包含stdbool.h而不是定义自己的bool类型。重新编译我的项目在使用的第三方代码bool或我自己的代码中都没有产生警告/错误。

为了更好地衡量,我尝试以某种方式对其进行修改,如果它在 C89 项目中编译,它仍然可以工作:

#if __STDC_VERSION__ >= 199901L
#include <stdbool.h>
#endif

// ...

#if __STDC_VERSION__ < 199901L
typedef enum _bool 
{ 
  false = 0, 
  true = 1 
} bool;
#endif
于 2018-07-18T11:45:19.727 回答
-2

首先,这些定义在 C 中逻辑上是不正确的。

C定义false为零和true非零,当然包括1但不仅如此。在许多情况下可能很危险:

只有当函数的返回值为 时,表达式if(GetValue() == true)才会计算为真1。这是极其危险的,并且可能是许多难以发现的错误的根源。

bool可以有任何值,就像int它背后的类型一样。

铸造不会改变任何东西:

#include <stdio.h>
#include <string.h>

typedef enum _bool 
{ 
  false = 0, 
  true = 1 
} bool;

int main(void) {

    bool x;

    x = 50;
    printf("%d\n", x);

    x = (bool)50;
    printf("%d\n", x);
}

https://ideone.com/nNHPLg

您将显式地将 int 值转换为零或一。例如:

bool x = !!something;

bool x = something ? true : false;

于 2018-07-18T10:56:44.643 回答