I am writing C++ header-only library doing some floating-point math. Since the library is header-only I realized that the library user sooner or later will include it into his project where -ffast-math
is enabled. And I cannot prevent the user from doing it except of writing in documentation: "Please, don't do it". The question is what can I do from my side to better support -ffast-math
?
I've tested my code and probably all rare issues are related to -finite-math-only
. It is not surprising since I don't do anything special like Kahan summation, but it is still an issue. If I understand -finite-math-only
correctly, then every x * y
multiplication for unbounded values x
and y
is UB, powering unbounded value to the power greater than 1 is UB, exp(x)
is UB, etc.
I am writing C++ header-only library doing some floating-point math. Since the library is header-only I realized that the library user sooner or later will include it into his project where -ffast-math
is enabled. And I cannot prevent the user from doing it except of writing in documentation: "Please, don't do it". The question is what can I do from my side to better support -ffast-math
?
I've tested my code and probably all rare issues are related to -finite-math-only
. It is not surprising since I don't do anything special like Kahan summation, but it is still an issue. If I understand -finite-math-only
correctly, then every x * y
multiplication for unbounded values x
and y
is UB, powering unbounded value to the power greater than 1 is UB, exp(x)
is UB, etc.
1 Answer
Reset to default 7And I cannot prevent the user from doing it [...]
Yes, you can.
#ifdef __FAST_MATH__
#error -ffast-math is not supported
#endif
Try on godbolt
See also how to use the gcc preprocessor macro __FAST_MATH__?
There are also (undocumented) predefined macros __ASSOCIATIVE_MATH__
, __FINITE_MATH_ONLY__
, __NO_MATH_ERRNO__
, __NO_SIGNED_ZEROS__
, __NO_TRAPPING_MATH__
, and __RECIPROCAL_MATH__
for the corresponding options, so to be a bit more careful, you could also test some or all of those.
HC SVNT DRACONES
. caveat elit (developer beware). – Eljay Commented Mar 17 at 15:18--ffast-math
is both GCC and CLang; MSVC has/fp:fast
which is similar in spirit. But it's not at all obvious which compiler(s) will have issues with your cod.e – MSalters Commented Mar 17 at 15:37