If I define a non-member function in a header, will it always be inlined by the compiler, or does the compiler choose based on its heuristics? I know that __inline is just a hint, is it the same with functions in headers?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Remember that including something from a header is no different than just typing it directly in the source file. So being in a header makes no difference as far as the compiler is concerned; it never knew it was there.
So when you define a function in a header file, and you include that header file in a file, it’s like you just typed the function straight into the file. So now the question is, “does the compiler choose to inline things based on heuristics?”
The answer is “it depends on the compiler”. The standard makes no guarantees about what gets inlined or not. That said, any modern compiler will be extremely intelligent about what it inlines, likely with heuristics.
However, we come to an interesting point. Imagine you have a function in a header and you include that header in multiple source files. You will then have multiple definitions of the function, across translation units, and this violates the one-definition rule. Ergo, you will get compile errors. (The linker error is usually something along the lines of: “Error, function x already defined in y”) What you can do is use the
inlinekeyword and you no longer violate the ODR.By the way
__inlineis non-standard. Contrary to your post, it’s usually a compiler extension which forces inlining, not hints it.inlineis the standard keyword, which was originally intended to hint at inlining. Like you say, most modern compilers completely ignore it in that regard and it’s only purpose nowadays is to give things internal linkage.