This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
When should I write the keyword 'inline' for a function/method?
So this is a question that has bugged me for a while and I can't get a definitive answer. My understanding is that a good compiler will generally realise when it is both safe and advantageous to in-line a function and, if optimisation is switched on, it will in-line all such functions weather they they are explicitly identified as in-line functions by the programmer or not. Also, a complier will recognise when it is not safe/sensible to in-line a function and will simply ignore the programmers request to in-line functions in such cases.
Thus, I would like to know what is the advantage of explicitly stating a function as in-line? As long as optimisation is switched on the compiler will in-line all the functions it deems sensible to in-line, and only those functions.
I have found some discussions around inline protecting against multiple definitions due to nested h files, but surely #ifdefine'ing the header source code is better practice and again renders the use of the key word inline void?
You're spot on about the compiler optimizations. You're just wrong in your assumption of what inline is. Despite the name inline is not for optimization. inline is primarily to "violate" the one definition rule with impunity. Basically, it tells the linker that many translation units can see that definition, so it should not barf on finding it on multiple translation units.
Some compilers may treat it as a hint to inline the function, but that's totally up to the compiler and perfectly valid to just ignore that hint.
Header guards only protect against multiple definitions on the same translation unit. They do not work across translation units.
Header guards don't protect against multiple definition errors.
Multiple definitions are encountered by the linker, and occur when the same definition is included into separate compilation units.
Related
I am aware that the keyword inline has useful properties e.g. for keeping template specializations inside a header file.
On the other hand I have often read that inline is almost useless as hint for the compiler to actually inline functions.
Further the keyword cannot be used inside a cpp file since the compiler wants to inspect functions marked with the inline keyword whenever they are called.
Hence I am a little confused about the "automatic" inlining capabilities of modern compilers (namely gcc 4.43). When I define a function inside a cpp, can the compiler inline it anyway if it deems that inlining makes sense for the function or do I rob him of some optimization capabilities ? (Which would be fine for the majority of functions, but important to know for small ones called very often)
Within the compilation unit the compiler will have no problem inline functions (even if they are not marked as inline). Across compilation units it is harder but modern compilers can do it.
Use of the inline tag has little affect on 'modern' compilers and whether it actually inlines functions (it has better heuristics than the human mind) (unless you specify flags to force it one way or the other (which is usually a bad idea as humans are bad at making this decision)).
Microsoft Visual C++ was able to do so at least since Visual Studio 2005. They call it "Whole Program Optimization" or "Link-Time Code Generation". In this implementation, the compiler will not actually produce machine code, but write the preprocessed C++ code into the object files. The linker will then merge all of the code into one huge code unit and perform the actual compilation..
GCC is able to do this since at least version 4.5, with major improvements coming in GCC 4.7. To my knowledge the feature is still considered somewhat experimental (at least in so far as many Linux distributions not using it). GCC's implementation works very similarly by first writing the preprocessed source (in its GIMPLE intermediate language) into the object files, then compiling all of the object files into a single object file which is then passed to the linker (this allows GCC to continue to work with existing linkers).
Many big C++ projects also do what is now being called "unity builds". Instead of passing hundreds of individual C++ source files into the compiler, one source file is created that includes all the other source files in the project. The original intent behind this is to decrease compilation times (since headers etc. do not have to be parsed over and over), but as a side-effect, it will have the same outcome as the LTO/LTCG techniques mentioned above: giving the compiler perfect visibility into all functions in all compilation units.
I jump between being impressed by my C++ compiler's (MSVC 2010) ingenuity and its stupidity. Some code that did pixel format conversion via templates, which would have resolved into 5-10 assembly instructions when properly inlined, got bloated into kilobytes(!) of nested function calls. At other times, it inlines so aggressively that whole classes disappear even though they contained non-trivial functionality.
This depends on your compilation flags. With -combine and -fwhole-program, gcc will do function inlining across cpp boundaries. I'm not sure how much the linker will do if you compile into multiple object files.
The standard dictates nothing about how a function can be inlined. And compilers can inline functions if they have access to their implementation. If you only have a header with binaries, it would be impossible. If it's in the same module, the compiler can inline the function even if it is in the cpp file.
This question already has answers here:
Benefits of inline functions in C++?
(14 answers)
Closed 8 years ago.
I learned that the functions in class must be 'inline' from a book
But, I can't understand why...
That book wasn't enough
I'm not native speaker in English, and so I'm very poor at searching in web described by Engilsh
And my country's web sites is very closed to students like me
So please answer me
I think
If a function(not inline) were in a class, the function' s stackframe (some adresses, arguments and so on) would be created repeatedly whenever compiler refer to that function
so this is why funtions in a class must be inline?
Sorry for my poor English
In the definition of C++, if a member function is declared inside the class it is understood by the compiler as being inline
Notice that inline (including the implicit one for functions declared inside class) is just a hint to the compiler, which may or may not actually inline that function on some (or all or none) of its call sites. Inlining is always an optimization which the compiler is free to implement or not, and it often enables other optimizations too.
BTW, some compilers may inline functions not marked as inline, and that may be even done across compilation units with the so called link-time-optimization (for g++ compile and link with -flto -O2)
I've working on a project at work where there's loads and loads of code in the header files. If I were using Visual Studio this wouldn't be an issue, as this has pre-compiled headers etc, but this is Linux GCC code.
Anyway, its starting to become a bit of an issue with compilation times. Of course the templates are going to have to remain in the headers etc, but most of this code could be extracted into implementation files and linked against as a static library. All of the projects uses these headers and get compiled each time, so it makes sense to create a static lib.
Implementations in the header files are in-lined, or is this only a hint, like the inline keyword? This code is VERY time critical and I'm concerned about moving the implementations out of the headers. Can I achieve the same thing if I use the inline keyword as opposed to having implementations in header files?
** UPDATE **
I know that inline is only a hint to the compiler. I'm not in control of everything in the project and I just want to move everything out of the headers into a library without affecting performance. Is this actually going to be a try it and see thing? I just want to keep performance exactly the same but enhance compile time.
The inline keyword is only a hint to the compiler that it may wish to inline that function. Its real purpose is to allow you to legally "violate" the one definition rule.
In order to inline a function its body has to be visible at the point of call, which typically means that if you move the function to an implentation file it may not be inlined anymore.
But keep in mind that most likely large functions in the header will not be inlined anyway. Also consider that in many cases inlined functions may actually be slower than called functions due to a variety of architecture-specific issues.
inline is a hint for optimization, but it is also used to work around ODR.
Consider using whole program optimization / link-time optimization instead. It allows you to have implementation in multiple files and basically everything has the same opportunity to be optimized (and inlined) as if it were in the same translation unit.
Your compile times become much quicker, but link times usually suffer, sometimes quite a bit. You don't need to enable it for debug builds though, so it can manifest a pretty immediate improvement to dev time.
If I were using Visual Studio this wouldn't be an issue, as this has pre-compiled headers etc
GCC has them too.
http://gcc.gnu.org/onlinedocs/gcc/Precompiled-Headers.html
The inline keyword does NOT mean that the function has to be implemented "in the line" where you define the function. As you know it is a hint for the compiler, to let it try compiling as if the few lines in the function were at the place where you call it. Thus avoiding the overhad of saving the adress to jump back, a vtable lookup etc.
Thinking it is faster called because it is in the header, is wishfull thinking (of the original guy who wrote the code).
Try it and move the implementation to the cpp file in a minimal example - main one object one inline function one call to it. Once implemented in the header and once in a cpp file. Then look at the assembly. No difference.
Lately I have started to put more and more functions into header files, mostly for convenience. But I fear I might be overdoing it, my headers are full of includes and I'm not sure if that's a good idea.
What are your rules of thumb for moving functions out of or into header files?
In case you're wondering, I'm talking about developing applications, not libraries.
Edit:
I guess it's helpful if I outline the pros/cons of inline (naturally) header functions versus implementation functions from my point of view:
Pro inline:
More clean/concise.
No need for signature duplication.
No need to change any Makefile to link against new files.
Instant ability to introduce template parameters.
Contra inline:
Increased compile time (I don't care that much)
Many includes in headers (Shouldn't be such a big issue if they use guards)
According to that, it seems like a good idea to put pretty much every function in headers, and I believe that's pretty close to what the STL and Boost are doing (although those are libraries, as opposed to my code).
One of my most inviolable rules: only function bodies which are inline are allowed in header files. Anything else is asking for trouble with multiple definitions in the link phase.
Headers should be left predominantly for declarations rather than definitions. I have exceptions to that rule (being the flexible type) but none of them involve non-inlined function bodies.
My rule of thumb is "Not in the header, unless you have to." And as for convenience, do you find increased compilation times convenient?
There are a few obvious technical aspects
- templates and inline functions must be in headers
- headers included from multiple translation units must be wary of the One Definition Rule
- more bluntly, you'd want a bloody good reason to even consider putting an out-of-line function implementation in a header, and I can't think of any times I've even been tempted.
So, the question boils down to:
inline in header versus out-of-line in implementation file?
Factors:
you say you're designing application level code not libraries, so you don't (currently) have to worry about other teams getting dependent on your code, nor minimise their need to recompile (versus just relink) by keeping implementation out of line
BUT if you're writing good code that has any potential to become useful to other teams, then you might find yourself wishing you'd kept implementation private
inline versus out-of-line typically represents about an order-of-magnitude overhead for trivial data get/set functions... if you have functions that are called repeatedly from performance critical code, then you've reason to prefer inlining
in-header implementation (especially if intermingled with the declarations) can often obfuscate the API, but sometimes actually makes the code more self-documenting
localisation and removed redundancy (of combining declaration/definitions) definitely removes potential for typos/errors and can often improve productivity
Bottom line: if you're finding yourself doing it more and more, then it's obviously working for you and there's no particular reason to think you're about to get burnt. Keep an eye out for the potential issues but don't over-engineer the heck out of stuff based on some hypothetical and unlikely-to-materialise concern.
A good coding standard will tell you to implement methods and functions in the source (cpp) file.
If you prefer it, you can implement templates and inline functions in the header.
Since this has been tagged as C++, why don't you seperate them into logical classes?
Normally I have one class declaration in a header file and it's definition in the corresponding source file.
The two rules I use are
1) If it's an inline functions
2) If it's a template function.
First, template function must be put in headers.
Besides, functions with an empty body, such as a default constructor or default but virtual destructor may be put in headers.
I never use inline because compiler don't guarantee that.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Inline functions vs Preprocessor macros
hello can somebody please explain what exactly does it mean, and what is the difference from regular macro(I know that it works during compile time and not preprocessor but so what?) thanks in advance for any help, looked in google but didn't find something understandable
(Assuming here that you're talking about C/C++.)
An inline function has its code copied into the points where it's called, much like a macro would.
The big reason you would use inline functions rather than macros to accomplish this is that the macro language is much weaker than actual C/C++ code; it's harder to write understandable, re-usable, non-buggy macros. A macro doesn't create a lexical scope, so variables in one can collide with those already in scope where it's used. It doesn't type-check its arguments. It's easy to introduce unexpected syntactic errors, since all a macro does is basically search-and-replace.
Also, IIRC, the compiler can choose to ignore an inline directive if it thinks that's really boneheaded; it can't do that with a macro.
Or, to rephrase this in a more opinionated and short way: macros (in C/C++, not, say, Lisp dialects) are an awful kludge, inline functions let you not use them.
Also, keep in mind that it's often not a great idea to mark a function as inline. Compilers will generally inline or not as they see fit; by marking a function inline, you're taking over responsibility for a low-level function that most of the time, the compiler's going to know more about than you are.
There is a big difference between macros and inline functions:
Inline is only a hint to the compiler
that function might be inlined. It
does not guarantee it will be.
Compiler might inline functions not
marked with inline.
Macro invocation does not perform
type checking, so macros are not type
safe.
Using function instead of a macro is
more likely to give you a nice and
understandable compiler output in
case there is some error.
It is easier to debug functions,
using macros complicates debugging a
lot. Most compilers will give you an
option of enabling or disabling
inlining, this is not possible with
macros.
The general rule in C++ is that macros should be avoided whenever possible.