【GCC】gcc编译参数之-fno-strict-aliasing

来源:互联网 发布:辽宁11选5遗漏数据 编辑:程序博客网 时间:2024/06/08 19:39

### Date: 2017/5/18

### Author: SoaringLee

先来看下gcc对strict aliasing的解释:

     Allows the compiler to assume the strictest aliasing rules applicable to the language being compiled. For C (and C++), this activates optimizations based on the type of expressions. In particular, an object of one type is assumed never to reside at the same address as an object of a different type, unless the types are almost the same. For example, an unsigned int can alias an int, but not avoid* or a double. A character type may alias any other type.
      要确保不违反这个规则,那么确实需要让不同指针指向同一个内存位置怎么办?对于已有的代码,违反的地方非常多,那么可以加gcc的-fno-strict-aliasing参数。其实在开启优化选项-O2和-O3的情况下,gcc会自动采用strict
aliasing进行编译器的优化。为了允许不同指针指向同一个内存位置,需要加gcc的编译选项: CFLAGS+=-fno-strict-aliasing。
      If optimization level is >= 2 in gcc-4.1, strict-aliasing is used, and this could cause probelms when a pointer is referencing to a different type of object and the object is refered thereafter by using this pointer. That is the case in this example. So you should force the compiler to not use strict-aliasing by a argument "-fno-strict-aliasing" if you want to use "-O2" or "-O3".
   错误实例:
          float f = j;          unsigned int* p = (unsigned int*)(&f);
在存在强制类型转换的情况下,采用-O1和采用-O2或-O3产生的运行结果是不同的。

原创粉丝点击