GCC优化选项的各种含义以及潜藏风险

GCC优化选项:一般的文档里不容易找到的-Os

在研究编译驱动的makefile的时候,发现GCC的命令行里面有一个-Os的优化选项。
    遍查GCC文档,发现了-O0, -O1, -O2, -O3,就是没有发现-Os。
    祭出GOOGLE大法搜了一下,终于发现这篇文章说明了-Os的作用:
http://www.linuxjournal.com/article/7269

   原来-Os相当于-O2.5。是使用了所有-O2的优化选项,但又不缩减代码尺寸的方法。
   详细的说明如下:
Level 2.5 (-Os)

The special optimization level (-Os or size) enables all -O2 optimizations that do not increase code size; it puts the emphasis on size over speed. This includes all second-level optimizations, except for the alignment optimizations. The alignment optimizations skip space to align functions, loops, jumps and labels to an address that is a multiple of a power of two, in an architecture-dependent manner. Skipping to these boundaries can increase performance as well as the size of the resulting code and data spaces; therefore, these particular optimizations are disabled. The size optimization level is enabled as:

gcc -Os -o test test.c

In gcc 3.2.2, reorder-blocks is enabled at -Os, but in gcc 3.3.2 reorder-blocks is disabled.

==============================
补充:在GCC的官方文档里又发现了关于-Os的说明:
http://gcc.gnu.org/onlinedocs/gcc-3.4.6/gcc/Optimize-Options.html#Optimize-Options

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

加了-Os选项导致的报错链接:http://spartan1.iteye.com/blog/1279619

加了-O2选项之后把错误的段错误优化掉的链接:http://bbs.chinaunix.net/thread-1799702-1-1.html

gcc优化选项编译指南:http://www.cnblogs.com/hoys/archive/2011/12/08/2280602.html

gcc优化产生的不正确结果:http://linux.solidot.org/article.pl?sid=07/11/19/0512218&from=rss

gcc O2选项造成的错误:http://bbs.csdn.net/topics/360056568。

O2选项-finline-small-functions有可能把小函数内联,但传入参数不正确,导致返回值不正确。实际开发中碰到过。

例如如下测试代码:

#include    <stdio.h>
#include    <errno.h>
#include    <sys/types.h>
#include    <sys/stat.h>
#include    <unistd.h>
#include    <errno.h>
#include         <fcntl.h>
int main ( int argc, char *argv[] )
{
    int fd1=-1;
    struct stat info1;
    fd1=open("/localhome/kana/lingc.txt", O_RDWR);
    printf("fd1=%d",fd1);
    if(fd1 > 0)
    {
        if(fstat(fd1,&info1)!=0)
        printf("failed to open fd1:%d;errorno:%d\n",fd1,errno);
        else printf("sucess");
        close(fd1);
    }

    return 0;
}

其中fstat函数就被内联了。


另外一则gcc优化-O2出现的bug:http://bbs.chinaunix.net/thread-1946983-1-1.html

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值