C 编译器是否能够跨 object 个文件进行优化?

Is C compiler able to optimize across object file?

我正在考虑 header-only 与 header 之间的源设计。我不确定 header&source 是否允许编译器跨 object 文件和跨链接进行优化?比如内联优化?

Header 文件和源文件通常编译为单个翻译单元(因为 headers 包含在源文件中)。所以,这不是问题(除非你有一个特殊的环境 headers是单独编译的)。

GCC 确实支持跨不同翻译单元的优化。参见 Link Time Optimization

有关详细信息,请参阅 -flto 选项的文档:

-flto[=n]

This option runs the standard link-time optimizer. When invoked with source code, it generates GIMPLE (one of GCC's internal representations) and writes it to special ELF sections in the object file. When the object files are linked together, all the function bodies are read from these ELF sections and instantiated as if they had been part of the same translation unit. To use the link-time optimizer, -flto and optimization options should be specified at compile time and during the final link. It is recommended that you compile all the files participating in the same link with the same options and also specify those options at link time.