Localize g++ compile options within code

478 Views Asked by At

I'm looking for a simple way to localize certain g++ (g++-4.9 to be specific) compile options to certain lines of code or at least targeted functions. I'm interested generally speaking, but also specifically to the -fast-math, -ffinite-math-only and -fno-signed-zeros options.

I presume that localization at the *.cpp file level is possible with make utility, but I'm hoping there is a way to enable it in the code itself, through #pragma or __attribute__ or something. I want to do this not only to minimize dependencies to external files (i.e. risk of incorrect makefile) but also to hopefully hyperlocalize certain FP behavior to specific equations within a function.

Alternatively, if localization of FP behavior by inline directives is NOT possible, what can I do to at least trigger a compile time error if desired compiler directive is NOT enabled in project build (e.g. makefile is lost or inappropriately modified).

I would presume that such inline optimization might be compiler specific, g++ in this case, but that is a compromise I'm willing to take.

3

There are 3 best solutions below

1
On BEST ANSWER

In gcc you can use function attribute optimize:

void f () __attribute__ ((optimize("fast-math"), optimize("finite-math-only"), optimize("no-signed-zeros")));
0
On

You might be able to turn on some bits of this with the fpmath option in a function attribute, but this was not clear to me from the docs. In light of that, I will focus on detection instead:

-fast-math already turns on -ffinite-math-only, so you don't need to worry about that. The docs for -fast-math say:

This option causes the preprocessor macro FAST_MATH to be defined.

Which means it can be detected via

#ifndef __FAST_MATH__
#error "The -fast-math compiler option is required"
#endif

I have not yet found a compile-time way to detect the presence of -fno-signed-zeros

0
On

I'm not sure that you are using the "localize" word correctly. Localization is related to adapting software to users of different human languages (French, Russian, Chinese...)

Perhaps you want to ask the compiler to optimize some functions with other optimization flags.

This is possible using #pragma GCC optimize etc... or using some function attributes