Issue
I have the following function:
template <typename Float, std::enable_if_t<std::is_floating_point_v<Float>, int> = 0>
constexpr Float inf2nan(Float x)
{
static_assert(std::numeric_limits<Float>::is_iec559);
return x * 0 + x;
}
This function will return NaN
if the input is infinity, otherwise just the input.
Unfortunately, using the -ffast-math
flag with GCC optimizes this away to just a ret
statement. I want my function to do the same with these flags enabled.
I've also tried replacing it with:
return std::isinf(x) ? std::numeric_limits<Float>::quit_NaN() : x;
but this does not get optimized by GCC and clang to the same output as my original function.
Is there a way (via comment or macro) to enable strict floating point math for just a single variable or function similar to Java's strictfp
keyword with GCC and clang? Alternatively, can I detect that fast math was enabled in my code and conditionally compile the latter version?
Solution
One way how to do that is to place all function definitions for which you want to have a certain set of compiler flags into on compilation unit (.cpp file) and compile this compilation unit with its own settings. That way you do not need to rely on compiler related in source settings.
How to exactly do that depends on your toolchain. In CMake you could create an OBJECT
library, and link that OBJECT
library with your executable. In a make file, it should also be straight forward to do that.
For in-source gcc specific solutions there is:
- Can I make my compiler use fast-math on a per-function basis?
- GCC - Enable compiler flags only on specific functions
Answered By - t.niese Answer Checked By - Pedro (WPSolving Volunteer)