【发布时间】:2016-03-01 07:18:06
【问题描述】:
我编写了一个非常简单的程序来测试 gcc -O2 选项,它会产生错误的行为。是gcc的bug吗?
我的 C 程序:
#include <stdio.h>
int main(int argc, char **argv)
{
unsigned long i = 0;
while (1) {
if (++i > 0x1fffffffUL) {
printf("hello\n");
i = 0;
}
}
}
当我用 -O1 编译它时,一切正常,i 在每个循环中加 1。但是当我用 -O2 编译它时,我会被忽略,每个循环都会输出“hello”。为什么 -O2 会导致这种错误行为? gcc的明显错误吗?我的 gcc 版本是 4.8.3 for cygwin,我已经尝试了一个新的,它也有同样的问题。
用-O1编译,汇编代码为:
Disassembly of section .text:
00000000 <_main>:
#include <stdio.h>
int main(int argc, char **argv)
{
0: 55 push %ebp
1: 89 e5 mov %esp,%ebp
3: 83 e4 f0 and $0xfffffff0,%esp
6: 83 ec 10 sub $0x10,%esp
9: e8 00 00 00 00 call e <_main+0xe>
e: b8 00 00 00 20 mov $0x20000000,%eax
unsigned long i = 0;
while (1) {
if (++i > 0x1fffffffUL) {
13: 83 e8 01 sub $0x1,%eax
16: 75 fb jne 13 <_main+0x13>
printf("hello\n");
18: c7 04 24 00 00 00 00 movl $0x0,(%esp)
1f: e8 00 00 00 00 call 24 <_main+0x24>
24: eb e8 jmp e <_main+0xe>
26: 90 nop
27: 90 nop
用-O2编译,汇编代码为:
Disassembly of section .text.startup:
00000000 <_main>:
#include <stdio.h>
int main(int argc, char **argv)
{
0: 55 push %ebp
1: 89 e5 mov %esp,%ebp
3: 83 e4 f0 and $0xfffffff0,%esp
6: 83 ec 10 sub $0x10,%esp
9: e8 00 00 00 00 call e <_main+0xe>
e: 66 90 xchg %ax,%ax
10: c7 04 24 00 00 00 00 movl $0x0,(%esp)
17: e8 00 00 00 00 call 1c <_main+0x1c>
1c: eb f2 jmp 10 <_main+0x10>
1e: 90 nop
1f: 90 nop
【问题讨论】:
-
该变量不是
volatile,除了创建无限循环之外,您的程序不会使用它。如果它没有优化掉,我会称之为错误。 -
@Ivan:请避免更改/扩展您的问题。创建一个新的(也许参考这个问题)。我回滚了最后一次添加。
-
好的。我已将我的新问题添加到 here
标签: c gcc optimization