当我在一步中编译所有东西时,GCC可以更好地优化东西吗? [英] Can GCC optimize things better when I compile everything in one step?

查看:213
本文介绍了当我在一步中编译所有东西时,GCC可以更好地优化东西吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

gcc优化代码,当我通过它 -O2 标志,但我想知道如果我真的能做到这一点,如果我编译所有源文件到目标文件和



下面是一个例子:

  // in ah 
int foo(int n);

//在foo.cpp中
int foo(int n){
return n;
}

//在main.cpp中
#includea.h
int main(void){
return foo(5)
}

//用于编译的代码全部
gcc -c -O2 foo.cpp -o foo.o
gcc -c -O2 main.cpp -o main.o
gcc -O2 foo.o main.o -o executable

通常,gcc应该内联 foo ,因为它是一个小函数, -O2 启用小功能,对吧?但是在这里,gcc在创建对象文件之前只看到 foo main 的代码,这样的任何优化,对吧?但是,我也可以这样编译:



<$>



< p $ p> gcc -O2 foo.cpp main.cpp -o executable

这会更快吗?

  // in foo.cpp 
int foo(int n) {
return n;
}

//在main.cpp中
#includefoo.cpp
int main(void){
return foo(5)
}

编辑:我看过 objdump ,它的反汇编代码显示只有 #includefoo.cpp的工作。

解决方案

您可能正在寻找链接时间优化(LTO),也称为整个计划优化。


gcc optimizes code when I pass it the -O2 flag, but I'm wondering how well it can actually do that if I compile all source files to object files and then link them afterwards.

Here's an example:

// in a.h
int foo(int n);

// in foo.cpp
int foo(int n) {
  return n;
}

// in main.cpp
#include "a.h"
int main(void) {
  return foo(5);
}

// code used to compile it all
gcc -c -O2 foo.cpp -o foo.o
gcc -c -O2 main.cpp -o main.o
gcc -O2 foo.o main.o -o executable

Normally, gcc should inline foo because it's a small function and -O2 enables -finline-small-functions, right? But here, gcc only sees the code of foo and main independently before it creates the object files, so there won't be any optimizations like that, right? So, does compiling like this really make code slower?

However, I could also compile it like this:

gcc -O2 foo.cpp main.cpp -o executable

Would that be faster? If not, would it be faster this way?

// in foo.cpp
int foo(int n) {
  return n;
}

// in main.cpp
#include "foo.cpp"
int main(void) {
  return foo(5);
}

Edit: I looked at objdump, and its disassembled code showed that only the #include "foo.cpp" thing worked.

解决方案

You may be looking for Link-Time Optimization (LTO), aka Whole Program Optimization.

这篇关于当我在一步中编译所有东西时,GCC可以更好地优化东西吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆