penalty for "inlined" classes - c++

Visual studio allow you to create "inlined" classes (if I am not mistaken with the name).
So class header and implementation all in one file.
H. file contain definitions and declarations of the class and functions, there is no .cpp file at all.
So I was wondering if there is any penalty for doing it that way? any disadvantages ?
Thanks a lot

any penalty for doing it that way? any disadvantages?
Yes. If you need to change the implementation of the class, since this is in a header file, all users of the class need to recompile, even though they should only be concerned with the interface. For some projects, this can be quite expensive.

You can put the complete implementation of a class in the header with any compiler. There's usually a penalty in terms of compile time -- the header will be compiled separately for each source file that includes it.
There may be a penalty in terms of code bloat as well -- putting the function definitions inside the class definition implicitly declares them inline, so there may be an increased likelihood of the compiler generating code for each of them individually instead of generating code in one place, and generating calls to it elsewhere.

A pretty bad idea if you ask me, especially for big projects. Take a look at Lakos' "Large-Scale C++ Software Design" to learn more about the drawbacks of such approach.

There's another potential penalty: Performance.
If you make too many functions inline, this leads to code bloat, which results in executables which functions and loops may not fit into the instruction cache of the target CPU.

No penalty.
But it also does not mean that the code is actually inlined.
They inline keyword is only a compier hint that is usually ignored as the compiler is usually much smarter than the developer in terms of knowing when to inline code.

The inline keyword is only a hint to the compiler to inline code. Visual Studio has a __forceinline specifier for functions that would make the compiler forcibly inline the function without a cost/benefit analysis.
About __forceinline : http://msdn.microsoft.com/en-us/library/z8y1yy88.aspx
The *.h file having all the definitions and declarations should not make any difference though except for compile times for large files.

There are two "penalties"
One will be assessed at compile time. If you have an unusually large project, you'll have lots of header files that the preprocessor will expand into one another with much more code. Changing one .h file will trigger a recompilation in all the files that include it.
The other is that it (may possibly) lead to larger binaries because that code is replicated in other object files.

Related

Header Implementations And The inline keyword for Optimization

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.

Inline in source file

I have a big class with lots of utility functions. those functions are very small and I would like them inlined.
The problem is they are all in a source file and should stay in the source file and not move to the header file (so I don't need to recompile everything every time one changes).
If I mark them as inline I get
symbols not found
Is there a way to make them inline or do I need to blindly trust the link time optimizer?
I need the code to be portable between clang 3 and gcc 4.6, but #defines based on compiler will be ok (so answer how to do it only in one of the compilers is fine too).
[These] functions are very small and I would like them inlined. [But] I don't [want] to recompile everything every time one changes.
You can't have both of these things. If a function is inlined, then you have no choice but to recompile all its callers when it changes. That's how inlining works. Even if you used a link-time optimizer to do it automatically at link time, you would still be paying the compilation-time cost of reprocessing all the callers.
AFAIK neither gcc 4.6 nor clang 3 have link-time optimizers that are up to scratch, by the way.
Editorial aside: No compiler that I know of has heuristics that are good enough to make manual inline annotations unnecessary, yet. Even VS2010, which I mentioned in the comments as an example of a link-time optimizer that is up to scratch, still needs quite a bit of advice about what to inline.
Place the implementation in an .inl file. Have only the necessary .cpp files #include it. This way changes to the implementation (touch .inl file) trigger recompile only of the dependent .cpp file. Changes to the definition (touch the .h file) trigger recompile of all files consuming the declaration.
This is a common practice for both inline functions and for template implementations. .inl files should be viewed basically as 'included cpp' files.
If you want a function to be inline'd you have to place it in a header file, unless it's only being used in the same source file. The reason being that the compiler needs the actual function definition in order to place the definition "inline" wherever it's being called, and then compile it up.
You can find further information: here and here.
You need the function mandatory inlined - you place it in the class definition.
One option could be to place the inline functions in a precompiled header file, which will speed up the compilation. But because of the nature of inlining functions all places they are used will have to be recompiled.
http://gcc.gnu.org/onlinedocs/gcc/Precompiled-Headers.html

Rules of thumb for putting functions in header files

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.

(C++) Whole class in .h file?

If I am creating a class with small functions that don't do much, is it acceptable to just put them all into the header file? So for a particular class, it's only just the .h with no .cpp to go with it.
Yes, that's acceptable. It will certainly compile. But also, if it makes the code organization cleaner, then that can be good. Most template definitions are already like this out of necessity, so you aren't doing anything unheard of. There can be some drawbacks of that class relies on other classes though. If you end up having to include the whole definition in other files that use the class, it may incur additional compile time compared to only having a brief class declaration.
You can measure your compilation times if this seems to be a real concern.
If you can get a copy, The c++ Programming Language (and many other books) have a detailed section about source code organization and the specific benefits of separating code into .h and .cpp files.
It depends what you are aiming for.
For a pet project, it's acceptable, but then anything is really.
For a real project, you need to ask yourself a number of questions:
do you have few dependencies ? (yes)
is your logic / implementation likely to change often ? (no, or see next question)
how much depends on this class ? (not much or much but it won't change)
If the responses satisfy you, then go ahead.
It is mainly a matter of dependency management. By putting the methods definition within the header, they are likely to get inlined by the compiler, which means that each time they change you'll have to recompile everything that depends on this class.
Templates do so, however templates generally have few dependencies (other includes) and you're relatively forced to proceed like so (though you can externalized non-template dependent code to cut down on dependencies).
For real big projects where dependency management is foremost, then I would advise against. In those projects a stable ABI and the ability to promote binary compatible changes are life-savers in case of issue and they are well worth the "slight" inconvenience for the developer.
In any case, please don't define the methods in the midst of the class. Even inlined you can define them after the class declaration. This makes it easier for people reading it (yourself in a few months) to get a grasp of the interface quickly.
Yes, it is acceptable. Moreover, if you do templates and you don't have a compiler with export support then you don't have a choice.
However, note that it can increase dependencies and thus make compilation slower.
It would be fine if you will use that header file in your future codes or projects, and if you want to share it with the others.
Depends on how you're linking. To avoid having to see messages such as redefinition of blah, previous definition in file blah.h on line 13 just put everything but the declaration in a .cpp.

C++: When is it acceptable to have code in the header file?

I've been taught to keep class definitions and code separate.
However, I've seen situations where people would often include some bits of code in the header, e.g. simple access methods which returns a reference of a variable.
Where do you draw the line?
Generally speaking, things you want the compiler to inline, or templated code. In either case, the code must be available to the compiler everywhere it's used, so you have no choice.
However, note that the more code you put in a header file, the longer it will take to compile - and the more often you'll end up touching header files, thus causing a chain reaction of slow builds :)
One reason to minimize the amount of code in headers is to minimize the amount of code to be recompiled when the implementation changes. If you don't care about that you can have any amount of code in headers.
Sometimes having the code in headers only is done intentionally to expose the code - ATL does that for eaxmple.
When developing a large C++ project, you need to be vigilant to make each .CPP file couple with as few header files as reasonably possible.
So I have a simple rule for "drawing the line":
If, by inlining the implementation, your header file now needs to include an additional header file, you should move the implementation out of the header and into the .CPP file.
Of course, that isn't the only reason not to inline, but this is a definite example of a line that shouldn't be crossed.
Inline functions
One/two line methods
Templates
But when the header grows in size, it will take more and more time to compile, so it is useful to use precompiled headers.
I would stick with the code in .c and .cpp files and headers stuff in .h, .hpp files. Reason is that when I download a .tar.gz or zip of source code, I'm always looking for the .h files for the header stuff and the .cpp files for the source. Many people are used to that so I think you should keep that style.
When you have code in the header file for simple getter/setter methods, it's more or less just fine because you either want to save some working time because of code maintenance (typing same method in header and implementation file), or because you actually want the method to be inline due to function call overhead in time critical places.
You will not only be subjected to slower builds, the linking time might be huge if you have a lot of classes visible more or less everywhere.
Another down side with mixing code between header and implementation files is readability. If you consistenly declare in header file and consistenly keep the code in the implementation file, it's easier to keep the same order between the methods. There are no missing gaps if you know what I mean.
Cheers !
Also note that you can wind up with some strange side-effects if you put code in a header file and aren't careful with your Makefile. I once had a bug due to code I changed in a header that was recompiled into some files but not others because the dependencies weren't correct in the Makefile. This isn't a big deal if you generate your Makefile automatically.
You will want code in the header if you wish to 'inline' the code. Otherwise, there are more advantages to sticking the implementation in the body.
It's up to you. Boost puts almost all of it's code in the header... and they're a well respected library.