0

我有一个 C 项目,其结构如下:

Project
- fileA.h
- fileA.c
+ subdirB
  - fileD.h

fileD.h 中有一个 bool 的 typedef 枚举:

typedef enum bool {
    false = 0,  /**< false (0) */
    true        /**< true (1) */
} bool;

在 fileA.c 中有几个使用 bool 作为参数的函数,因此包含了 fileD.h:

#include "subdirB/fileD.h" // header with bool typedef
#include "fileA.h"         // own header with foo declaration
...
int foo (bool bar) {
 ...
 return 0;
}
...

这些函数是全局的,所以它们的声明被添加到头文件A.h中:

int foo (bool bar);

然而,最后一点给我一个错误,“标识符布尔未定义”......我不明白为什么会这样?

4

2 回答 2

4

你包括在内fileD.hfileA.h?为了声明一个接受 bool 的函数,编译器需要知道 bool 是什么。

于 2013-06-11T17:18:06.327 回答
1

如前所述,fileA.h需要注意其中bool定义的类型,fileD.h以便函数原型为foo()有效。

但是,请注意,由于 yourbool不是内置类型,而是,因此不会对所有非零值进行enum隐式转换。true所以不要指望里面的代码foo()看起来像:

if (bar == true) {
    //...
}

在一般情况下工作。您可以通过宏替换来缓解这种情况foo()

#define foo(x) foo(!!(x))

如果您有许多需要bool. 但是这个!!技巧本身可以为你将非零值变成非零值1

于 2013-06-11T19:02:31.700 回答