简体   繁体   中英

Is the order of function definitions important for inlining in C++

When one function calls another, and inlining is desired, is the order of the definitions of the two functions important? Assume that the two definitions occur in the same translation unit.

I am primarily interested in what the C++ standard says about it, if anything. However, if you have important information about the inlining behavior in specific compilers, I would be interested in that too. Please assume that no link-time optimization occurs (is disabled).

Specifically, are the following two versions equally likely to achieve inlining according to the C++ standard?

Version one:

inline void foo() { ... }
void bar() { ... foo(); ... }

Version two:

inline void foo();
void bar() { ... foo(); ... }
void foo() { ... }

EDIT: Please note that this question is not about the effectiveness of the inline keyword with respect to achieving inlining in general. I specifically ask about whether the standard says anything about the order of function definitions in relation to achieving inlining.

The C++ standard doesn't make any imposition here. Compilers are free to inline or not in any situation they see fit. The inline keyword may have no effect other than allowing multiple definitions of the same function.

Most compilers will be able to inline any function that is available to the translation unit, regardless of the order it appears in the source. Forward declarations generally only affect what names are available at a given point in the source file, not anything about the final output of the binary.

In reality the inline keyword has less to do with inlining code and more to do with allowing legal violation of the one definition rule. The main purpose of inline is to tell the compile that a function may appear in multiple translation units (and that it will have the same definition in each one). This allows it to avoid multiple definition errors at the link stage.

Using the inline keyword is no guarantee that the compiler will inline the function at all - it's just a suggestion. Additionally many compilers will inline functions not marked as inline if the definition can be seen within the translation unit and the compiler deems it worthwhile. I strongly suspect that either version you show would either be inlined or not by a particular compiler.

In short, let the compiler decide whether or not to inline, and write your code in the most readable way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM