在<stdbool.h>
的特定情況下,我們選擇避免依賴於config.h
,並依靠C(或C++)編譯器告訴我們什麼是好的。代碼包含這個頭文件,並且這個頭文件將這個混亂文件整理出來。已知可在Mac OS X,Linux,Solaris,HP-UX,AIX,Windows上工作。實際的頭文件名不是ourbool.h
,但是我已經修改了它的標頭保護和註釋,所以它看起來好像是它的名字。這些評論引用了C99標準,以執行許可證。請注意,如果已經包含<stdbool.h>
,它也可以正常工作,並且在包含<stdbool.h>
後(如果得到此更正並非100%無痛苦),它將正常工作。定義__bool_true_false_are_defined
對於這種交互工作至關重要。 (如果你的代碼是由其他人使用,則不能強制他們不使用<stdbool.h>
自己,之前或者你的頭被包含後。)
#ifndef OURBOOL_H_INCLUDED
#define OURBOOL_H_INCLUDED
/*
** Ensure that type bool with constants false = 0 and true = 1 are defined.
** C++ (ISO/IEC 14882:1998/2003/2011) has bool, true and false intrinsically.
** C (ISO/IEC 9899:1999) has bool, true and false by including <stdbool.h>
** C99 <stdbool.h> also defines __bool_true_false_are_defined when included
** MacOS X <dlfcn.h> manages to include <stdbool.h> when compiling without
** -std=c89 or -std=c99 or -std=gnu89 or -std=gnu99 (and __STDC_VERSION__
** is not then 199901L or later), so check the test macro before defining
** bool, true, false. Tested on MacOS X Lion (10.7.1) and Leopard (10.5.2)
** with both:
** #include "ourbool.h"
** #include <stdbool.h>
** and:
** #include <stdbool.h>
** #include "ourbool.h"
**
** C99 (ISO/IEC 9899:1999) says:
**
** 7.16 Boolean type and values <stdbool.h>
** 1 The header <stdbool.h> defines four macros.
** 2 The macro
** bool
** expands to _Bool.
** 3 The remaining three macros are suitable for use in #if preprocessing
** directives. They are
** true
** which expands to the integer constant 1,
** false
** which expands to the integer constant 0, and
** __bool_true_false_are_defined
** which expands to the integer constant 1.
** 4 Notwithstanding the provisions of 7.1.3, a program may undefine and
** perhaps then redefine the macros bool, true, and false.213)
**
** 213) See 'future library directions' (7.26.7).
**
** 7.26.7 Boolean type and values <stdbool.h>
** 1 The ability to undefine and perhaps then redefine the macros bool, true,
** and false is an obsolescent feature.
**
** Use 'unsigned char' instead of _Bool because the compiler does not claim
** to support _Bool. This takes advantage of the license of paragraph 4.
*/
#if !defined(__cplusplus)
#if __STDC_VERSION__ >= 199901L
#include <stdbool.h>
#elif !defined(__bool_true_false_are_defined)
#undef bool
#undef false
#undef true
#define bool unsigned char
#define false 0
#define true 1
#define __bool_true_false_are_defined 1
#endif
#endif /* !_cplusplus */
#endif /* OURBOOL_H_INCLUDED */
顯然,如果你想允許HAVE_STDBOOL_H
的可能性,你可能,但它不是必需的。如果定義了HAVE_CONFIG_H
,您也可以決定如何操作,但不再需要。
要使用此功能,你的頭將包含:
#ifndef YOURHEADER_H_INCLUDED
#define YOURHEADER_H_INCLUDED
...other #includes as needed...
#include "ourbool.h" /* Or #include "project/ourbool.h" */
...other material...
extern bool boolean_and(bool lhs, bool rhs);
...other material...
#endif /* YOURHEADER_H_INCLUDED */
的yourheader.h
ourbool.h
的確切位置並不重要,只要它是你聲明的類型,函數或(滅亡的思想)使用變量之前bool
類型。
非常聰明。謝謝! – Sebastian