简体   繁体   中英

How do you forward declare the `bool` type in a C header file?

Consider a header file, myheader.h with the following function header:

bool isValid(char c);

And whose implementation file, myimplementation.c , contains:

#include <stdbool.h>

bool isValid(char c) {
  return c == 'Y' || c == 'N';
}

If one would like to avoid include ing stdbool.h in the header file, how does one properly "forward declare" the bool datatype in the header file?

If you want "bool", you should include "stdbool.h":

https://en.cppreference.com/w/c/types/boolean

Boolean type support library

The C programming language, as of C99, supports Boolean arithmetic with the built-in type _Bool (see _Bool). When the header <stdbool.h> is included, the Boolean type is also accessible as bool.

Macros

Macro name Expands to ---------- ---------- bool _Bool true integer constant 1 false integer constant 0 __bool_true_false_are_defined integer constant 1

If including <stdbool.h> in every source file that uses "bool" really annoys you, Ted Lyngmo made a good suggestion: simply define your own header, and include stdbool.h there.

First, there is no need to declare bool ; you can simply declare the function as _Bool isValid(char c); .

Second, C 2018 7.18 2 says <stdbool.h> defines bool to be a macro that is replaced by _Bool . You can simply do this yourself with #define bool _Bool . 7.18 4 says that a program may undefine and redefine bool . To be pedantic and extra safe in conforming to that, you could use:

#undef bool
#define bool _Bool

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM