使用 flto 的要求

Requirements to use flto

如果我想用 -flto 编译我的项目,用 --enable-gold 构建 gcc 就足够了吗?还是我还需要构建 gold 并用它替换 ld?我需要任何其他标志吗?即我正在这样做

gcc -flto one.c two.c

根据https://gcc.gnu.org/wiki/LinkTimeOptimization#Requirements,

Despite the "link time" name, LTO does not need to use any special linker features. The basic mechanism needed is the detection of GIMPLE sections inside object files. This is currently implemented in collect2. Therefore, LTO will work on any linker already supported by GCC.

此外,-fuse-linker-pluginGCC documentation 表示:

This option is enabled by default when LTO support in GCC is enabled and GCC was configured for use with a linker supporting plugins (GNU ld 2.21 or newer or gold).

所以你根本不需要 gold,即使你想使用特殊的 "linker plugin" 功能从库档案中的目标文件中获取优化信息。


-flto documentation中有用法示例。要么

      gcc -o myprog -flto -O2 foo.c bar.c

      gcc -c -O2 -flto foo.c
      gcc -c -O2 -flto bar.c
      gcc -o myprog -flto -O2 foo.o bar.o

会起作用。


GCC 4.9 起,您甚至不需要 -flto 进行链接:

The only important thing to keep in mind is that to enable link-time optimizations you need to use the GCC driver to perform the link-step. GCC then automatically performs link-time optimization if any of the objects involved were compiled with the -flto.

GCC 5 开始:

Contrary to earlier GCC releases, the optimization and target options passed on the link command line are ignored.