Is there a macro (#define ...) somewhere in the bowels of Arduino IDE or core header files which tells me at compile time(!), if the double
data type for a given platform/board is a true double precision floating point number (64 bit width) or "only" an alias for a single precision float (32 bit width)?
With Arduino, both can be the case. 8-bit AVR boards have double
equal to float
, ARM-based boards (like Arduino Zero) support "true" double precision.
I am working on a library which implements some bit-banging of floating point numbers (both single and double precision). Due to the low-level nature of the problem, there must be separate functions for float
and double
. I would like to do somthing like that:
uint32_t function_for_float(float f) {
// function body here...
}
#if defined(HAS_64_BIT_DOUBLE)
uint64_t function_for_double(double d) {
// function body here...
}
#endif
That way, a compile time error would be generated if somebody tried to use the "double" version on platforms which do not support the "true" double data type. I want the compiler error to be generated, because function_for_double()
will do silently "the wrong thing" when fed a single precision float, leading potentially to difficult-to-debug problems.
Right now, I am defining a macro constant for every relevant board I own, like this:
#if defined(ARDUINO_SAMD_ZERO) \
|| defined(SAMD_FEATHER_M0_EXPRESS) \
|| defined(ADAFRUIT_FEATHER_M4_EXPRESS)
#define HAS_64_BIT_DOUBLE
#endif
But this is ugly and not future-proof (new boards can/will become available...).
Any suggestions?
1 Answer 1
The double
data type is almost universally 8-bytes long, so you could
simply
#if !__AVR__
# define HAS_64_BIT_DOUBLE
#endif
Gcc provides a more specific macro though: __SIZEOF_DOUBLE__
, which
has the same value as sizeof(double)
. But I do not know whether it is
provided by other compilers.
-
1Perfect! I will make use macros
__SIZEOF_DOUBLE__
and__SIZEOF_DOUBLE__
, even if they are gcc/g++ specific. The Arduino IDE uses g++ as its backend, anyway, so this is "good enough" for me.Andy– Andy2021年05月26日 08:51:40 +00:00Commented May 26, 2021 at 8:51 -
1Just verified that
__SIZEOF_DOUBLE__ == 4
on an Arduino Pro Mini (AVR 328p) and__SIZEOF_DOUBLE__ == 8
on an Adafruit Feather M0 (ARM Cortex-M0+ / SAMD21). Thanks a lot! I have selected your answer as the correct one.Andy– Andy2021年05月26日 09:00:29 +00:00Commented May 26, 2021 at 9:00
static_assert(sizeof(double) == 8)
in the code of my "double function". However, then the complete library .cpp file will not compile on platforms wheredouble
ist only four bytes. This is what brought me to think about conditional complilation in the first place. I would like to generate a compiler error only if sombody tries to use the double version when he/she shouldn't. Somewhere in Arduino there surely must be definied that double is equal to float? I hope(d) to use this as a hook somehow...