Post by Chris VineOn Thu, 23 Apr 2020 05:46:06 -0700 (PDT)
Post by Ãö TiibPost by Frederick Gotham#include <stdbool.h>
int EnableDebug(bool en_dbg)
{
/* Do Something */
return 0;
}
I compile this C source file to an object file. Later I want to use it in a C++ program, and so I need to declare this function in a C++ header. But which one do I use?
extern "C" int EnableDebug(bool);
extern "C" int EnableDebug(int);
My understanding in C is that "bool" is a typedef for "_Bool". But is "_Bool" just a regular 'int' or is it something smaller (e.g. char) ?
So use bool and require C code to #include <stdbool.h>. AFAIK C _Bool
and C++ bool are same type (in every ABI in practice) but I do not
know if it is formally guaranteed somewhere or not.
I should either (i) use int for both C and C++, or (ii) use _Bool/bool
for both C and C++, and not mix ints with bools. bool(0.5) is
different in both languages from int(0.5).
As I recall it when I looked into it there was no requirement for C's
_Bool to be the same size as C++'s bool, although it would be a brain
dead implementation which made them different sizes. As an aside, I
cannot now recall whether the incorporation of parts of C into C++ in
Annex C formally requires C's ints to be the same size as C++'s ints
but I think it is implicit from the incorporation of parts of C's
standard library into C++ that they must be.
I expect that technically the C++ compiler is a separate implementation
from the C compiler, even when they are both part of the same package
(like gcc). In C++, "int" used by functions in the C library must match
"int" used by other parts of C++, but there is no requirement that it
match "int" used by a C compiler, or by any other compiler on the
system. The same applies between two C compilers on the same system.
But as you say, it would take a brain-dead implementation to end up with
anything different in "int" (or bool/_Bool) on a given platform. These
sorts of things are specified in platform ABI's and any compiler for C
or C++ will follow the ABI for the platform.
(I know of a couple of C compilers where the size of "int" can be
changed from the command line, but these won't be of concern to most
people.)