3

我注意到我的代码在 -O3 处中断,但在 -O2 处没有。我尝试一一应用标志,我发现

gcc -O1 -finline-functions code.c

休息;和

gcc -O1 -fno-inline-functions code.c

作品。

“中断”是指它可以编译,但运行不正确。

我应该在哪里寻找这个错误?我可以发布代码,但由于它的 SLOC 为 1.5k,我宁愿不发布整个内容。

版本:

$ uname -a
Linux xxxx.xxxx 2.6.18-308.20.1.el5 #1 SMP x86_64 x86_64 x86_64 GNU/Linux
$ gcc -v
Using built-in specs.
Target: x86_64-redhat-linux
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --enable-shared --enable-threads=posix --enable-checking=release --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-libgcj-multifile --enable-languages=c,c++,objc,obj-c++,java,fortran,ada --enable-java-awt=gtk --disable-dssi --disable-plugin --with-java-home=/usr/lib/jvm/java-1.4.2-gcj-1.4.2.0/jre --with-cpu=generic --host=x86_64-redhat-linux
Thread model: posix
gcc version 4.1.2 20080704 (Red Hat 4.1.2-54)
4

1 回答 1

5

我发现了这个错误:

int foo() {
  return 5;
}
int bar() {
  foo(); // <-- no return statement!
}
int main() {
  printf("%d", bar());
}

看,即使没有 return 语句bar(),值 5 已经在返回值寄存器中。main()在返回寄存器中获取值,认为它来自 bar,但实际上它来自 foo。这是未定义的行为,但只有在编译器尝试内联时才会爆炸bar()。解决办法是把returnbar()

值得称赞的是,如果您打开 -Wall,它确实会警告您

code.c:63: warning: control reaches end of non-void function

我通过手动将__attribute__ ((noinline))(感谢 sjs!)应用到函数中找到了这一点,直到我的代码正常工作

于 2013-06-25T17:53:14.663 回答