Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

interfacing with stdbool.h C++

In a project I am interfacing between C++ and a C library that uses stdbool.h defined as such.

#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

Some structures have bool members. So if I have one of these structures defined as local variables within a C++ function and pass it to a C function the sizes are inconsistent between C++ and C as bool is one bye in C++ and 4 in C.

Does anyone have any advice to how to overcome this without resorting to my current solution which is

//#define bool _Bool
#define bool unsigned char

Which is against the C99 standard for stdbool.h

like image 591
JProgrammer Avatar asked Aug 24 '08 23:08

JProgrammer


1 Answers

I found the answer to my own question by finding a more compatible implementation of stdbool.h that is compliant with the C99 standard.

#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

This is taken from the Ada Class Library project.

like image 189
JProgrammer Avatar answered Sep 19 '22 17:09

JProgrammer