gpt4 book ai didi

c++ - 与 stdbool.h C++ 接口(interface)

转载 作者:IT老高 更新时间:2023-10-28 23:00:50 26 4
gpt4 key购买 nike

在一个项目中,我在 C++ 和一个使用 stdbool.h 定义的 C 库之间进行交互。

#ifndef _STDBOOL_H
#define _STDBOOL_H

/* C99 Boolean types for compilers without C99 support */
/* http://www.opengroup.org/onlinepubs/009695399/basedefs/stdbool.h.html */
#if !defined(__cplusplus)

#if !defined(__GNUC__)
/* _Bool builtin type is included in GCC */
typedef enum { _Bool_must_promote_to_int = -1, false = 0, true = 1 } _Bool;
#endif

#define bool _Bool
#define true 1
#define false 0
#define __bool_true_false_are_defined 1

#endif

#endif

有些结构有 bool 成员。因此,如果我将这些结构之一定义为 C++ 函数中的局部变量并将其传递给 C 函数,则 C++ 和 C 之间的大小不一致,因为 bool 在 C++ 中是一个再见,在 C 中是 4。

有没有人对如何在不诉诸我目前的解决方案的情况下克服这个问题有任何建议

//#define bool _Bool
#define bool unsigned char

这违反了 stdbool.h 的 C99 标准

最佳答案

我找到了符合 C99 标准的 stdbool.h 的更兼容实现,从而找到了我自己问题的答案。

#ifndef _STDBOOL_H
#define _STDBOOL_H

#include <stdint.h>

/* C99 Boolean types for compilers without C99 support */
/* http://www.opengroup.org/onlinepubs/009695399/basedefs/stdbool.h.html */
#if !defined(__cplusplus)

#if !defined(__GNUC__)
/* _Bool builtin type is included in GCC */
/* ISO C Standard: 5.2.5 An object declared as
type _Bool is large enough to store
the values 0 and 1. */
/* We choose 8 bit to match C++ */
/* It must also promote to integer */
typedef int8_t _Bool;
#endif

/* ISO C Standard: 7.16 Boolean type */
#define bool _Bool
#define true 1
#define false 0
#define __bool_true_false_are_defined 1

#endif

#endif

这取自 Ada Class Library项目。

关于c++ - 与 stdbool.h C++ 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25461/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com