What is the correct way to enable strict aliasing warnings in g++? Does VC++ 10 implement those rules?
The answer typically is to type pun, often the methods used violate strict aliasing rules. Sometimes we want to circumvent the type system and interpret an object as a different type. This is called type punning, to reinterpret a segment of memory as another type.
GCC compiler makes an assumption that pointers of different types will never point to the same memory location i.e., alias of each other. Strict aliasing rule helps the compiler to optimize the code.
In C, C++, and some other programming languages, the term aliasing refers to a situation where two different expressions or symbols refer to the same object.
"Strict aliasing is an assumption, made by the C (or C++) compiler, that dereferencing pointers to objects of different types will never refer to the same memory location (i.e. alias each other.)"
Use -fstrict-aliasing
for g++
. I also use -Wstrict-aliasing=2
to see warnings related to possible violations of strict aliasing rules.
They're enabled automatically by -O2
because it needs to use them to do some of the optimizations. Definitely combine it with the warning (-Wall
does the trick) to make sure you aren't building potentially buggy code. Otherwise you can use -fstrict-aliasing
as seen in another answer to enable them.
I'm not sure about VC++10 however.
VC++ 10 enables the strict aliasing rule with /O1 and above. I use the test program(with count value 6) in chapter 'BENEFITS TO THE STRICT ALIASING RULE' of here. And get following asm code. You can see the load of b is done only once.
00A910AE movzx edx,word ptr [edx+2] //Load of b
00A910B2 xor eax,eax
00A910B4 xor ecx,ecx
00A910B6 add dword ptr [esp+eax*4+34h],edx //Loop start
00A910BA add eax,1
00A910BD adc ecx,edi
00A910BF jne main+76h (0A910C6h)
00A910C1 cmp eax,6
00A910C4 jb main+66h (0A910B6h) //Loop end
But looks like there isn't a way to enable the warning for breaking this rule.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With