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

前端 未结 8 1243
余生分开走
余生分开走 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:24

    It depends. Most compilers (linkers, really) support this kind of optimizations. But in order for it to be done, the entire code-generation phase pretty much has to be deferred to link-time. MSVC calls the option link-time code generation (LTCG), and it is by default enabled in release builds, IIRC.

    GCC has a similar option, under a different name, but I can't remember which -O levels, if any, enables it, or if it has to be enabled explicitly.

    However, "traditionally", C++ compilers have compiled a single translation unit in isolation, after which the linker has merely tied up the loose ends, ensuring that when translation unit A calls a function defined in translation unit B, the correct function address is looked up and inserted into the calling code.

    if you follow this model, then it is impossible to inline functions defined in another translation unit.

    It is not just some "simple" optimization that can be done "on the fly", like, say, loop unrolling. It requires the linker and compiler to cooperate, because the linker will have to take over some of the work normally done by the compiler.

    Note that the compiler will gladly inline functions that are not marked with the inline keyword. But only if it is aware of how the function is defined at the site where it is called. If it can't see the definition, then it can't inline the call. That is why you normally define such small trivial "intended-to-be-inlined" functions in headers, making their definitions visible to all callers.

提交回复
热议问题