C++ – How to detect ‘strict aliasing’ at compile time

coptimizationpointers

'Strict aliasing' optimization needs special care from the source code, s.a. using a union instead of pointer casts. Is there a way to detect using preprocessor directives (#if/else) whether the compiler is trying to do such optimizations?

I would like to maintain the old and non-strict-aliasing-prepared code path for processors and compilers that don't care. It seems faster.

Edit: GCC predefined macros does not seem to have anything about aliasing. In other words, I'm most interested on gcc 4.x, but also in a general solution (which does not seem to exist).

Best Answer

Completely implementation dependant - you need to check the docs for your specific compiler(s). And when asking questions like this, it's a good idea to mention which compiler(s) you are using.

A semi-portable way to do this is from your Makefile - define different targets for aliased & unaliased versions and define your own STRICT_ALIASING (or whatever) preprocessor symbol for the aliased version.