当我在一步中编译所有东西时,GCC可以更好地优化东西吗? [英] Can GCC optimize things better when I compile everything in one step?
问题描述
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屋!