C++ ISO standard says, that:
"A function defined within a class definition is an inline function."
Are there any compilers that IGNORE this rule?
(please, do not mistake inline with inlineD - my question is if there is a compiler, that wont put there that inline suggestion that it should)
You seem to be misunderstanding what "inline" means. It doesn't mean functions will automatically be inlined; according to 7.1.2-2 it indicates that inline substitution is to be preferred.
Therefore, you can't tell whether a function is labeled inline or not from the code, since the compiler is free to decide one way or another. It's just a compiler hint.
The standard says that all compilers can ignore inline requests, whether implicit or explicit. Whether or not they do so will nornally depend on whether the function can practically be inlined - for example recursive functions cannot be.
Edit: Just to clarify - the questioner is ignoring this, from the previous para in the standard to that he quoted from:
An implementation is not required to
perform this inline substitution at
the point of call
I suspect your test is flawed. You can't test with only one such file whether the compiler ignores the inline specifier or not.
You need to include the header containing the inline function definition and include it into multiple implementation files that are then linked together. If you get linker errors about multiple defined instances of that functions, then the compiler is ignoring the inline specifier regarding its most important property: Allowing it to be defined multiple times across the entire program while still retaining the same address for it and its local static variables.
What your test probably checks is whether or not the compiler inlines the call to the function, which is actually only a hint to the compiler and only a small of many other more important consequences of the inline specifier. If the compiler does not not inline a call to the function, it is fine doing so. The standard does not require it to do anything in this matter.
See my answer to a very similar question: When is "inline" ineffective? (in C)
Summary: inline is only required to allow multiple definitions. Any function calling changes is purely optional.
Compiler's usually inline based on the number of calls to the function, the number of pseudo-instructions in the function, and a bunch of other things. Take a look at the GCC documentation on optimization options for an idea of how it does things. Basically, the inline keyword is just a hint that bumps up the likelihood that the compiler will inline. The actual decision to inline is usually complex.
Related
I think I fully understand the meaning of the inline keyword in C++. Specifically it means two only semi-related things:
The ODR rule is relaxed for the function declared inline. Thus you can have the same function symbol defined in multiple TUs without getting an error when linking them. This allows a function to be defined in a header.
It is a suggestion to the compiler that it should replace invocations of the functions with a copy of the function's compiled code, rather than a call instruction to the address of the function symbol.
I can understand that these two meanings are necessarily related in one direction: 2 must imply 1. #2 requires that the function definition be available to all TUs that invoke the function. Therefore the function definition must exist in multiple TUs. Therefore the ODR needs to be relaxed to avoid linker errors.
But my question is about the other direction - why is the language designed such that 1 must imply 2?
It seems reasonable, in some cases and for some design decisions, to want to be able to relax the ODR for a function, without suggesting to the compiler that it should actually inline the function code. If I have a function I want to distribute via a header file I must mark it as inline to relax the ODR (#1). But now I am forced into #2 even if I have specific knowledge that in terms of performance, the function is not a good candidate for inlining.
My understanding is that this unwanted implication does not exist for template functions. The ODR is automatically relaxed for template functions (as it must be). That allows me to use inline only as a performance suggestion.
I understand that distributing functions in header files, as opposed to e.g. a static library, can be a bad idea. But as a programmer, there is some possibility that I know what I am doing, and I would like that flexibility. I have that flexibility with template functions so why not non-template functions?
Or is there a portable way to relax the ODR without suggesting that the function be inlined? E.g. on MSVC you can do this:
__declspec(noinline) inline void Foo() {}
Here inline relaxes the ODR, but __declspec(noinline) requests that the compiler not actually inline the call. But __declspec(noinline) isn't portable.
Thanks!
But __declspec(noinline) isn't portable.
You can make it portable to all implementations that have an analogous attribute by using a platform detection macro. GCC and Clang have __attribute__((noinline)).
Another approach is to simply not care. The compiler still has the option to ignore the preference that it perceives to have been implied. If the inline expansion would be expensive (because the function is big), a smart compiler should refrain from expanding it.
!! Specific on frequently used methods like getter & setter. !!
I have no idea when the keyword inline should be used. Ofc I know what it does, but I still have no idea.
According to an interview with Bjarne Stroustrup he said:
My own rule of thumb is to use inlining (explicitly or implicitly) only for simple one- or two-line functions that I know to be frequently used and unlikely to change much over the years. Things like the size() function for a vector. The best uses of inlining is for function where the body is less code than the function call and return mechanism, so that the inlined function is not only faster than a non-inlined version, but also more compact in the object core: smaller and faster.
But I often read that the compiler automatically inline short functions like getter, setter methods (in this case getting the size() of a vector).
Can anyone help?
Edit:
Coming back to this after years and more experience the high performance C+++ programming, inline can indeed help. Working in the games industry even forceinline sometimes makes a difference, since not all compilers work the same. Some might inline automatically some don't.
My advice is if you work on frameworks, libraries or any heavily used code consider the use of inline, but this is just general advice anyway since you want such code to be fully optimized for any compiler. Always using inline might not be the best, because you'll also need the class definition for this part of the code. Sometimes this can increase compilation times if you can't use forward declarations anymore.
another hint: you can use C++14 auto return type deduction even with seperating the function definition:
MyClass.h
class MyClass
{
int myint;
public:
auto GetInt() const;
}
inline auto MyClass::GetInt() const { return myint; }
all in one .h file.
Actually, inline keyword is not for the compiler anymore, but for the linker.
That is, while inline in function declaration still serves for most compilers as a hint, on high optimization setting they will inline things without inline and won't inline things with inline, if they deem it better for the resulting code.
Where it is still necessary is to mark function symbols as weak and thus circumvent One Definition Rule, which says that in given set of object files you want to make into a binary, each symbol (such as function) shall be present only once.
Bjarne's quote is old. Modern compilers are pretty smart at it.
That said, if you don't use Link Time Code Generation, the compiler must see the code to inline it. For functions used in multiple .cpp files, that means you need to define them in a header. And to circumvent the One Definition Rule in that case, you must define those functions as inline.
Class members defined inside the class are inline by default, though.
The below speaks specifically to C++:
The inline keyword has nothing to do with inlining.
The inline keyword allows the same function to be defined multiple times in the same program:
Every program shall contain exactly one definition of every non-inline function or variable that is odr-used in that program; no diagnostic required.
§3.2 [basic.def.odr]
Attaching meaning beyond this to the inline keyword is erroneous. The compiler is free to inline (or not) anything according to the "as-if rule":
A conforming implementation executing a well-formed program shall produce the same observable behavior as one of the possible executions of the corresponding instance of the abstract machine with the same program and the same input.
§1.9 [intro.execution]
Considering what compiler optimizations can do, the only use of inline I have today is for non-template function whose body is defined inside headers files outside class bodies.
Everything is defined (note: defined != declared) inside class bodies is inline by default, just as templates are.
The meaning of inline in fact is: "Defined in header, potentially imported in multiple sources, just keep just one copy of it" told to the linker.
May be in c++35 someone will finally decide to replace that keyword with another one more meaningful.
C++ standard Section 7.1.2 Point 2:
(...) The inline specifier indicates to the implementation that
inline substitution of the function body at the point of call is to be
preferred to the usual function call mechanism. An implementation
is not required to perform this inline substitution at the point of
call (...)
In other words instead of havin a single code for your function, that is called several times, the compiler may just duplicate your code in the various places the function is called. This avoids the little overhead related to the function call, at the cost of bigger executables.
Be aware that inline keyword may be used also with namespaces, but with a very different meaning. Members of an inline namespace can be used in most respects as though they were members of the enclosing namespace. (see Standard, section 7.3.1 point 8).
Edit:
The google style guide recommends to inline only when a function is ten lines or less.
I'm answering the question my self!: Solution: After a few performance tests, the rule of thumb from Stroustrup is right! inlining Short functions like the .size() from vector can improve the performance (.size() calls are used frequently). But the impact is only noticeable for FREQUENTLY used functions. If a getter/setter method is used a lot, inlining it might increase the performance.
Stroustrup:
Don’t make statements about “efficiency” of code without first doing
time measurements. Guesses about performance are most unreliable.
C++ allows you to annotate functions with the inline keyword. From what I understand, this provides a hint (but no obligation) to the compiler to inline the function, thereby avoiding the small function calling overhead.
I have some methods which are called so often that they really should be inlined. But inline-annotated functions need to be implemented in the header, so this makes the code less well-arranged. Also, I think that inlining is a compiler optimization that should happen transparently to the programmer where it makes sense.
So, do I have to annotate my functions with inline for inlining to happen, or does GCC figure this out without the annotation when I compile with -O3 or other appropriate optimization flags?
inline being just a suggestion to compiler is not true & is misleading.There are two possible effects of marking a function inline:
Substitution of function definition inline to where the function call was made &
Certain relaxations w.r.t One definition rule, allowing you to define functions in header files.
An compiler may or may not perform #1 but it has to abide to #2. So inline is not just a suggestion.There are some rules which will be applied once function is marked inline.
As a general guideline, do not mark your functions inline just for sake of optimizations. Most modern compilers will perform these optimizations on their own without your help. Mark your functions inline if you wish to include them in header files because it is the only correct way to include a function definition in header file without breaking the ODR.
Common folklore is that gcc always decides on its own (based on some cost heuristics) whether to inline something or not (depending on the compiler/linker options, it can even do so at link time). You can observe this sometimes when using -Winline where gcc warns that an inline hint was ignored, it often even gives a reason.
If you want to know exactly what is going on, you probably have to read the source code of it, or take the word of someone who read it.
I was told long ago to make short functions/methods that are called often inline, by using the keyword inline and writing the body in the header file.
This was to optimize the code so there would be no overhead for the actual function call.
How does it look with that today? Does modern compilers (Visual Studio 2010's in this case) inline such short functions automatically or is it still "necessary" to do so yourself?
inline has always been a hint to the compiler, and these days compilers for the most part make their own decisions in this regard (see register).
In order to expand a function inline, the compiler has to have seen the definition of that function. For functions that are defined and used in only one translation unit, that's no problem: put the definition somewhere before it's used, and the compiler will decide whether to inline the function.
For functions that are used in more than one translation unit, in order for the compiler to see the definition of the function, the definition has to go in a header file. When you do that, you need to mark the function inline to tell the compiler and linker that it's okay that there's more than one definition of that function. (well, I suppose you could make the function static, but then you could end up wasting space with multiple copies)
Enable warning C4710, this will warn you if a function which you define as inline is not inlined by the compiler.
Enable warning C4711, this will warn you if the compiler inlines a function not designated for inlining.
The combination of these two warnings will give you a better understanding of what the compiler is actually doing with your code and possibly whether it is worth designating inline functions manually or not.
Generally speaking, the inline keyword is used more now to allow you to "violate" the one definition rule when you define a function in a header than to give the compiler a hint about inlining. Many compilers are getting really good at deciding when to inline functions or not, as long as the function body is visible at th4e point of call.
Of course if you define the function only in a source file non-inline, the compiler will be able to inline it in that one source file but not in any other translation unit.
Inlining may be done by a compiler in the following situations:
You marked the function as inline and
it's defined in a current translation unit or in file that it's included in it;
compiler decides that it's worth doing so. According to the MSDN
The inline keyword tells the compiler that inline expansion is preferred.
The compiler treats the inline expansion options and keywords as suggestions.
You used the __forceinline keyword (or __ attribute __((always_inline)) in gcc). This will make compiler to skip some checks and do the inlining for you.
The __forceinline keyword overrides the cost/benefit analysis and relies on the judgment of the programmer instead.
Microsoft compiler can also perform cross module inlining if you have turned on link time code generation by passing /GL flag to the compiler or /LTCG to the linker. It's quite clever in making such optimizations: try to examine the assembly code of modules compiled with /LTCG.
Please note, that inlining will never happen if your function is:
a recursive one;
called through a pointer to it.
Yes, modern compilers will (depending on various configuration options) automatically choose to inline functions, even if they're in the source (not header) file. Using the inline directive can give a hint.
Aside from your main point (what amount of placing inline instructions in code is useful as of compilers today), keep in mind that inline functions are just a hint to the compiler, and are not necessarily being compiled as inline.
In short, yes, compilers will decide whether or not your function becomes inline. You can check this question:
Does the compiler decide when to inline my functions (in C++)?
In C++, do methods only get inlined if they are explicitly declared inline (or defined in a header file), or are compilers allowed to inline methods as they see fit?
The inline keyword really just tells the linker (or tells the compiler to tell the linker) that multiple identical definitions of the same function are not an error. You'll need it if you want to define a function in a header, or you will get "multiple definition" errors from the linker, if the header is included in more than one compilation unit.
The rationale for choosing inline as the keyword seems to be that the only reason why one would want to define a (non-template) function in a header is so it could be inlined by the compiler. The compiler cannot inline a function call, unless it has the full definition. If the function is not defined in the header, the compiler only has the declaration and cannot inline the function even if it wanted to.
Nowadays, I've heard, it's not only the compiler that optimizes the code, but the linker can do that as well. A linker could (if they don't do it already) inline function calls even if the function wasn't defined in the same compilation unit.
And it's probably not a good idea to define functions larger than perhaps a single line in the header if at all (bad for compile time, and should the large function be inlined, it might lead to bloat and worse performance).
Yes, the compiler can inline code even if it's not explicitly declared as inline.
Basically, as long as the semantics are not changed, the compiler can virtually do anything it wants to the generated code. The standard does not force anything special on the generated code.
Compilers might inline any function or might not inline it. They are allowed to use the inline decoration as a hint for this decision, but they're also allowed to ignore it.
Also note that class member functions have an implicit inline decoration if they are defined right in the class definition.
Compilers may ignore your inline declaration. It is basically used by the compiler as a hint in order decide whether or not to do so. Compilers are not obligated to inline something that is marked inline, or to not inline something that isn't. Basically you're at the mercy of your compiler and the optimization level you choose.
If I'm not mistaken, when optimizations are turned on, the compiler will inline any suitable routine or method.
Text from IBM information Center,
Using the inline specifier is only a
suggestion to the compiler that an
inline expansion can be performed; the
compiler is free to ignore the
suggestion.
C Language Any function, with the exception of main, can be declared or
defined as inline with the inline
function specifier. Static local
variables are not allowed to be
defined within the body of an inline
function.
C++ functions implemented inside of a class declaration are
automatically defined inline. Regular
C++ functions and member functions
declared outside of a class
declaration, with the exception of
main, can be declared or defined as
inline with the inline function
specifier. Static locals and string
literals defined within the body of an
inline function are treated as the
same object across translation units;
Your compiler's documentation should tell you since it is implementation dependent. For example, GCC according to its manual never inlines any code unless optimisation is applied.
If the compiler does not inline the code, the inline keyword will have the same effect as static, and each compilation unit that calls the code will have its own copy. A smart linker may reduce these to a single copy.
The compiler can inline whatever it wants in case inlining doesn't violate the code semantics and it can reach the function code. It can also inline selectively - do inline when it feels it's a good idea and not inline when it doesn't feel it's a good idea or when it would violate the code semantics.
Some compilers can do inlining even if the function is in another translation unit - that's called link-time code generation.
Typical cases of when inlining would violate code semantics are virtual calls and passing a function address into another function or storing it.
Compiler optimize as he wants unless you spec the opposite.
The inline keyword is just a request to the compiler. The compiler reserves the right to make or not make a function inline. One of the major factor that drives the compiler's decision is the simplicity of code(not many loops)
Member functions are declared inline by default.(The compiler decides here also)
These are not hard and fast rules. It varies according to the compiler implementations.
If anybody knows other factors involved, please post.
Some of the situations where inline expansion may NOT work are:
For functions returning values, if a loop, a switch, or a goto exists
For function not returning values, if a return statement exits;
If functions contain static variables
If inline functions are recursive.
Inline expansion makes a program run faster because the overhead of a function call and return statement is eliminated. However, it makes the program to take up more memory because the statements that define the inline functions are reproduced at each point where the function is called. So, a trade-off becomes necessary.
(As given in one of my OOP books)