Will C++ linker automatically inline functions (without “inline” keyword, without implementation in header)?

前端 未结 8 1241
余生分开走
余生分开走 2021-02-07 06:42

Will the C++ linker automatically inline \"pass-through\" functions, which are NOT defined in the header, and NOT explicitly requested to be \"inlined\" through the

8条回答
  •  滥情空心
    2021-02-07 07:16

    Is it common ? Yes, for mainstream compilers.

    Is it automatic ? Generally not. MSVC requires the /GL switch, gcc and clang the -flto flag.

    How does it work ? (gcc only)

    The traditional linker used in the gcc toolchain is ld, and it's kind of dumb. Therefore, and it might be surprising, link-time optimization is not performed by the linker in the gcc toolchain.

    Gcc has a specific intermediate representation on which the optimizations are performed that is language agnostic: GIMPLE. When compiling a source file with -flto (which activates the LTO), it saves the intermediate representation in a specific section of the object file.

    When invoking the linker driver (note: NOT the linker directly) with -flto, the driver will read those specific sections, bundle them together into a big chunk, and feed this bundle to the compiler. The compiler reapplies the optimizations as it usually does for a regular compilation (constant propagation, inlining, and this may expose new opportunities for dead code elimination, loop transformations, etc...) and produces a single big object file.

    This big object file is finally fed to the regular linker of the toolchain (probably ld, unless you're experimenting with gold), which performes its linker magic.

    Clang works similarly, and I surmise that MSVC uses a similar trick.

提交回复
热议问题