When should I use -inl.h files? - c++

I just noted this item in the Google C++ Coding Style Guide - and I don't quite get it.
If I put an inline method or function in a file other than the header included by other files, it will not be a method of the class; and it will only be usable to bits of code which include it. So why even have such -inl.h files at all?
Also, why do we even want to inline long functions anyways? (i.e. other than in the case of templates, when we have to put the code in the header files for instantiation)

I just noted this item in the Google C++ Coding Style Guide - and I don't quite get it.
Do take that guide with a pinch of salt. Many of the guidelines are intended to help interact with Google's legacy codebase, and aren't particularly good advice for general C++ development.
So why even have such -inl.h files at all?
There's no particularly good reason; I don't do that myself. Some people like them because it minimises the amount of stuff in the main header file, which users of the header generally want to read, and separates out the implementation details, which they generally don't care about.
Also, why do we even want to inline long functions anyways?
Sometimes, we must: template definitions must be available in any translation unit that instantiates the template, so they (usually) need to be in headers.
Sometimes, we want to: by implementing a function inline in a header, we don't have to worry about building and linking a separate translation unit for it. This can make it more convenient to distribute a library; possibly at the cost of longer build times.

This is often done for long function templates. The regular header my_functions.h only contains the declarations, and the implementation file my_functions-inl.h contain the implementations. The reason is that function templates cannot be put in .cpp files. Note that the X.h file includes the X-inl.h file, not the other way around.
Other libraries have different naming conventions: e.g. some of the Boost libraries use .hpp for template headers and .ipp for template implementation files.

According to latest Google coding style, it is no longer allowed
https://google.github.io/styleguide/cppguide.html#Variable_Names
Prefer placing the definitions for template and inline functions in the same file as their declarations. The definitions of these constructs must be included into every .cc file that uses them, or the program may fail to link in some build configurations. If declarations and definitions are in different files, including the former should transitively include the latter. Do not move these definitions to separately included header files (-inl.h); this practice was common in the past, but is no longer allowed.

Related

How to properly declare functions in C++? [duplicate]

I know this maybe quite subjective, but are there any general rules for situations when it is not necessary for code to be split into two files?
For example is the class is extremely small, or if the file simply holds some global definitions or static functions? Also, in these cases, should the single file be a .cpp file or a .h file?
On the technical side, whenever you need to obey the one definition rule you have to separate declarations from definitions, since you will need to include the declarations many times in multiple translation units, but you must only provide one single definition.
In aesthetic terms, the answer could be something like "always", or "systematically". In any case, you should always have a header for every logical unit of code (e.g. one class or one collection of functions); and the source file is one that is possibly optional, depending on whether or not you have everything defined inline (exempting you from ODR), or if you have a template library.
As a meta strategy, you should seek to decouple the compilation units as much as possible, so that you can include only what's needed in a fine-grained way. This allows your project to grow without having compilation times become unbearable, and it makes it much easier to reuse code in other projects.
I favor putting code in .hpp files but am very often compelled to put the implementation in the .cpp for any of the following reasons:
Reducing build time. This is the #1 reason to use .cpp files... and the reason most code you find in .hpp files is small and simple. When the implementation changes, you don't want to have to rebuild every .cpp that includes it.
When the function's linkage is important. For example, if the function is exported as a library (e.g. DLL) function, it's important that it select a single compilation unit to live in. Or for static / global instances. This is also important for distributing an import header for a DLL.
When you wish to hide implementation details when distributing a library
The definition and declaration are not identical. This can be the case with respect to constness of arguments.
You want a "clean" overview of the interface in the .hpp file. I find that with modern code tools and increasing familiarity with single-code-file languages like javascript / C# / inline C++, this is not a strong argument.
You explicitly do not want the function to be declared inline. Although, it won't matter; the optimizing compiler will likely inline if it wants to.
There are logical motivations for keeping code inline in a .hpp file:
Why have two files when you can have one?
Duplicating the declaration / function headers is unnecessary maintenance and feels redundant. We have code analysis tools to show interfaces.
The concept that inline / template code must be put in a header and other code is put in a .cpp is arbitrary. If we are forced to put inline code in a .hpp file, and this is OK, then why not put all code in a .hpp file?
I am pretty sure though that the tradition of separate .cpp and .hpp files is far stronger than the reasoning however.
I know this maybe quite subjective, but are there any general rules
for situations when it is not necessary for code to be split into two
files?
Split the code into header and source whenever you can.
Generally, this shouldn't be done in next cases :
the code consists of template classes and functions (unless you
explicitly instantiate templates in the source file)
the header consists only of inline functions
should the single file be a .cpp file or a .h file?
Should be the header file (.h).
The rule I use is the following:
Whenever you can put code into a cpp file, do it.
The reasons are multiple:
Header files serve as rudimentary documentation. It is better not to clutter them with code.
You can also use pimpls at some places if you feel like, for the reason above.
It reduces compilation times:
whenever you change a .cpp, only this file will be recompiled.
whenever a header is included, it only contains the minimal amount of code needed
It allows you to assess more easily which part of your code depends on which other part, just by looking at which headers are included. This point mandates another rule of mine:
Whenever you can forward declare a class instead of including a header, do it.
This way, the .cpp files carry the dependency information between parts of your source. It also lowers build times.
I know this maybe quite subjective, but are there any general rules for situations when it is not necessary for code to be split into two files?
It's not always subjective; you will very good reasons to separate them in large projects. It's good to get into the practice of separating them, and learning when it is and is not appropriate to separate definition from declaration. It's hard to answer your question without knowing how complex your codebase will become.
For example is the class is extremely small
It's still not necessarily a bad idea to separate them, in general.
or if the file simply holds some global definitions
The header should not contain global definitions which require static construction, unless necessary.
or static functions?
These do not belong anywhere in C++. Use inline, or anonymous namespace. If you mean within a class' body, "it depends on the instruction count, if you are hoping it will be inlined".
Also, in these cases, should the single file be a .cpp file or a .h file?
The single file should be a header. Rationale: You should not #include cpp files.
And don't forget that intermodule (aka link-time) optimizations are getting better and better.
C++ compilation times are long, and it's very very very time consuming to fix this after the fact. I recommend that you get into the practice of using cpp files before your build times and dependencies explode.

C++: including a class definition in a header file

A number of posts are pretty adamant that source code should not go in a header and that header files should be kept to a minimum. I've been sticking to this with my own code, but I want to use someone else's code to achieve a particular goal (the code is documented here http://ftp.arl.mil/random/).
I notice that this is basically one giant header file which defines a class. Is it OK to leave this in a header file? Should I copy it all to a .cpp file and create a new .h that just declares the functions, structures etc?
If I split it into a .cpp and a .h as I propose, will it work? Or do classes need to be in the header to be accessed by all source code?
Declarations (stating that something exists) that need to be seen in more than one cpp file should go in header files. Declarations that are local to a single cpp file should be in the cpp file itself.
Definitions (providing the body of a function or allocating/initializing variables) should usually go in cpp files, but not always.
The question you need to understand is does the compiler have enough information to do its job if it has seen the header file and not the corresponding cpp file.
For example: you can call a method if the compiler has seen the declaration (the method prototype) -- unless the method is generic (a templated method or a member of a templated class) or inline in which case the compiler needs to have seen the definition (the method body) too.
Therefore normal methods go in cpp files; templated methods go in header files; inline methods go in header files (and so on).
There are other situations in which definitions belong in header files including static member constants. It all comes back to giving the compiler the information it needs one one hand vs minimizing coupling between separate compilable units on the other. Again there are no hard-and-fast rules, just guidelines coupled with the knowledge and experience of the developer writing the code.
.h files are usually shared between many .cpp files.
The global variables and function code should not be in the header files, because it would make duplicates during linking.
Constants, defines, function headers and class declarations are fine in header files. You don't have to declare the same thing multiple times and you can share the definitions between .cpp files.
source code should not go in a header and that header files should be
kept to a minimum.
This is a popular assertion, and while it may generally not be bad advice, you should not draw absolute conclusions from it. Sometimes headers should be minimal and not include definitions. Sometimes the opposite is true. There are reasons why you would do one or the other, but "people say" is not one of them.
Consider the C++ Standard Library. Better yet, consider Boost. Some prestigious C++ experts have said that Boost is the most well-designed C++ library in history. But if you look at the libraries you'll see that they are basically just giant header files for the most part. How does this reconcile with what "they" say?
The point is this: you must understand the reasons why certain files are designed the way they are, and make up your own mind about what is Right and Wrong for each situation.
Should I copy it all to a .cpp file and create a new .h that just
declares the functions, structures etc?
I would say probably not. This sounds like a recipe for a maintenance nightmare to me. It would be my first instinct to use the 3rd party library they way the library's author intended it to be used. That way you won't be off the support grid, and you won't introduce a new set of complications that you will be completely on your own to figure out. Unless you have a specific, provable reason to alter the architecture of the library, don't. "They say" isn't a good enough reason for me.

Header and cpp or just cpp files - best practise?

Looking around at different code bases I see a variety of styles:
Class "interfaces" defined in header file and the actual impl in a cpp file. In this approach the headers look well defined and easy to read but the cpp files look confusing as it's just a list of methods.
The second approach i see is just to put everything in a single class cpp file. These class files contain the definition and actual method impls in the body of the class definition. This approach looks better to me (more like Java and c#).
Which style should I be using?
For all but the simplest programs, style #2 is simply impossible. If you #include a .cpp file with function definitions from multiple other .cpp files, the definitions get added to multiple object files (.o / .obj) and the linker will complain about clashing symbols.
Use style #1 and learn to live with the confusion.
The former - interfaces in header files and class bodies in implementation files. You'll find this causes you fewer problems when working on large systems.
In C++ why have header files and cpp files?
C++ doesn't use "interfaces" they use classes - base/derived classes. I use one file to define class/and its implementation methods if the project is small and separate files if the project is large.
In java, I pack them up into one package then import it once in need.
Since you tagged with c++, go for first style. I don't find it confusing, for a Java programmer, it may seem different, but in C++, you are always going to use this approach.
In fact in my favorite IDE (MSVS), I open header file, and cpp file side by side. Makes looking up prototypes, and class declaration easy.
And when you have a dozen classes; a dozen .h files, and another dozen .cpp file, will make your work simpler. Because, when you want just to see, what a class does, you just open relevant .h file, and take a look at class members, and maybe short comments. You don't need to wade through several lines deep code.
Conclusion : The style options you gave, are option only for a small code, typically single file, with very few methods etc. Otherwise, it is not even a option. (#Thomas has given the reason why #2 is not even a option)
Header (HPP):
The header includes the declarations of your code, particularly function declarations. Technically speaking classes are defined in header-files, but again, the member functions are just declared.
Code in other files will include just this header and retain all necessary information from there.
Implementation (CPP):
The implementation includes the definition of functions, member-functions and variables.
Rationale:
Header-files gives a developer (a external user of your code) a plain overview and just offers the external available code (i.e. easy to read, only the information necessary for users).
Header-files allow the compiler to check the implementation for correctness
Header-files allow the compiler to check external code for correctness
Header-files allow for seperate-compilation. You need to keep in mind. that in former times, computers doesn't have enough resources to keep everything in main-memory during a compilation process. Header files are small, while implementation files are big.
Use #style 1, even for simple programs. So you can learn easily to work with. That maybe look outated today, especially in background of modern Multi-Pass-Compilers. But seperate header-files are even today beneficial. Rumours about the next C++-Standard appeared, as far as I know something like symbol export ( Java or C#) will be possible. But don't nail me down on this!
Notes:
- member-functions which are defined inside a class are by default inline, normally you don't want this
- use always defined guards
If you are developing large project, you'll find the first approach helps you a lot. The second approach may help you in small project. As your project becomes larger, management of complexity is a big issue of software development, and the first approach turns out to be a better choice.
What I do is:
write .cpp files, with the method names prefixed with the class name
in the .h file, create an empty class, with the appropriate name, then use a cogapp generator script, cog_addheaders.py, to insert the declarations, eg:
.cpp file: WeightsPersister.cpp
.h file: WeightsPersister.h
This way I get:
fast compilation (just needs to recompile the .cpp file, unless I change the class interface)
few issues with circular declarations
acceptably low tedious mindless manual work :-)

When should I not split my code into header and source files?

I know this maybe quite subjective, but are there any general rules for situations when it is not necessary for code to be split into two files?
For example is the class is extremely small, or if the file simply holds some global definitions or static functions? Also, in these cases, should the single file be a .cpp file or a .h file?
On the technical side, whenever you need to obey the one definition rule you have to separate declarations from definitions, since you will need to include the declarations many times in multiple translation units, but you must only provide one single definition.
In aesthetic terms, the answer could be something like "always", or "systematically". In any case, you should always have a header for every logical unit of code (e.g. one class or one collection of functions); and the source file is one that is possibly optional, depending on whether or not you have everything defined inline (exempting you from ODR), or if you have a template library.
As a meta strategy, you should seek to decouple the compilation units as much as possible, so that you can include only what's needed in a fine-grained way. This allows your project to grow without having compilation times become unbearable, and it makes it much easier to reuse code in other projects.
I favor putting code in .hpp files but am very often compelled to put the implementation in the .cpp for any of the following reasons:
Reducing build time. This is the #1 reason to use .cpp files... and the reason most code you find in .hpp files is small and simple. When the implementation changes, you don't want to have to rebuild every .cpp that includes it.
When the function's linkage is important. For example, if the function is exported as a library (e.g. DLL) function, it's important that it select a single compilation unit to live in. Or for static / global instances. This is also important for distributing an import header for a DLL.
When you wish to hide implementation details when distributing a library
The definition and declaration are not identical. This can be the case with respect to constness of arguments.
You want a "clean" overview of the interface in the .hpp file. I find that with modern code tools and increasing familiarity with single-code-file languages like javascript / C# / inline C++, this is not a strong argument.
You explicitly do not want the function to be declared inline. Although, it won't matter; the optimizing compiler will likely inline if it wants to.
There are logical motivations for keeping code inline in a .hpp file:
Why have two files when you can have one?
Duplicating the declaration / function headers is unnecessary maintenance and feels redundant. We have code analysis tools to show interfaces.
The concept that inline / template code must be put in a header and other code is put in a .cpp is arbitrary. If we are forced to put inline code in a .hpp file, and this is OK, then why not put all code in a .hpp file?
I am pretty sure though that the tradition of separate .cpp and .hpp files is far stronger than the reasoning however.
I know this maybe quite subjective, but are there any general rules
for situations when it is not necessary for code to be split into two
files?
Split the code into header and source whenever you can.
Generally, this shouldn't be done in next cases :
the code consists of template classes and functions (unless you
explicitly instantiate templates in the source file)
the header consists only of inline functions
should the single file be a .cpp file or a .h file?
Should be the header file (.h).
The rule I use is the following:
Whenever you can put code into a cpp file, do it.
The reasons are multiple:
Header files serve as rudimentary documentation. It is better not to clutter them with code.
You can also use pimpls at some places if you feel like, for the reason above.
It reduces compilation times:
whenever you change a .cpp, only this file will be recompiled.
whenever a header is included, it only contains the minimal amount of code needed
It allows you to assess more easily which part of your code depends on which other part, just by looking at which headers are included. This point mandates another rule of mine:
Whenever you can forward declare a class instead of including a header, do it.
This way, the .cpp files carry the dependency information between parts of your source. It also lowers build times.
I know this maybe quite subjective, but are there any general rules for situations when it is not necessary for code to be split into two files?
It's not always subjective; you will very good reasons to separate them in large projects. It's good to get into the practice of separating them, and learning when it is and is not appropriate to separate definition from declaration. It's hard to answer your question without knowing how complex your codebase will become.
For example is the class is extremely small
It's still not necessarily a bad idea to separate them, in general.
or if the file simply holds some global definitions
The header should not contain global definitions which require static construction, unless necessary.
or static functions?
These do not belong anywhere in C++. Use inline, or anonymous namespace. If you mean within a class' body, "it depends on the instruction count, if you are hoping it will be inlined".
Also, in these cases, should the single file be a .cpp file or a .h file?
The single file should be a header. Rationale: You should not #include cpp files.
And don't forget that intermodule (aka link-time) optimizations are getting better and better.
C++ compilation times are long, and it's very very very time consuming to fix this after the fact. I recommend that you get into the practice of using cpp files before your build times and dependencies explode.

Using C++ headers (.h) vs headers plus implementation (.h + .cpp), what are the disadvantages?

As a novice C++ programmer I have always put my classes interface in .h files and implementation in .cpp files. However I have recently tried C# for a while and I really like its clean syntax and way to organize files, in particular there is no dinstinction between headers and implementation, you usually implement a class for each .cs file and you don't need headers.
I know that in C++ this is also possible (you can code "inline" functions in .h files), but up to now I have always seen a clear distinction between .h and .cpp files in C++ projects. What are the advantages and disadvantages of this approach?
Thank you
There's a few ways that separating the two help in C++. Firstly, if you'd like to update a library without changing an interface then having the code in the C++ file means that you simply can update the library rather than the library plus the headers. Secondly it hides the implementation. That is, it forces people to look at your class only in terms of the interface, the thing that should concern them if the code is well written. Finally, there's a sort of asthetic cleanness with interface + documentation that comes with this separation. It's something you have to get used to but after a while it'll feel natural (opinion.)
Don't forget build times.
Putting implementation code in header files makes them more likely to be changed. And changing header files will cause rebuilds of all the CPP files that include them, which in turn increases build times. This can be significant in larger projects.
I am also a fan of keeping the implementation hidden from users of my libraries. Unfortunately this doesn't work for template classes.
My rule of thumb: keep declarations in .H files, keep definitions in .CPP files.
it's cooler to have the symbols defined at one place for the case you wanted to compound C++ with already compiled binaries (typicly when using a library). imagine you need to define external symbols for global stuff in your binaries. if you had .cpp and .h code in the same file you would have to define the symbols for your binaries for every such file. in two files way you could have just the one .h with definitions for binaries and a lot of .cpp files that use it.
The main difference is that something implemented inside a .h file will be placed in every compilation unit that includes that header, this will create redundancy during the compile phase in the final binary executable.. while splitting with .h and .cpp will compile it in a single object file that is later linked against the other objects files by having just one compiled binary code that implements that header file.
In addition if you declare things just inside a .h you are not able to share variables and structures between more other .cpp files..
It's interesting to note that C# seems to be going in the C/C++ direction to some extent recently, with the introduction of partial classes.
The particular advantage of this in the IDE is that the Visual Studio designer will modify the part of the class that deals with visual controls, or data members, and their layout without any worries about mucking up the methods (application logic) that reside in a separate file.
I would echo #wheaties and add a few further items
Compilation is easier (may be it's just me), I've never been able to get compilation to work just right if you modify the header only (as in all the implementation files that have included it). I believe in Makefiles you have to add the dependencies manually which is a real pain in very large scale projects (again could just be me). So if you have your code in implementation files, then changes simply mean recompiling that particular file - very useful when you want to do quick changes, build and test.
Let me re-iterate the hiding aspect, most often you don't want people to know the implementation details due to the sensitive nature of the code, and thus only expose the headers plus the pre-built libraries, and the separation is key here.
Forward declarations, neat trick where you don't need to include the implementation details of a class in the header file if it's not being "used" in any of the code in the header, but then in the implementation file you can include the real header and "it all works nicely" (helps if you have cyclic dependencies - why you have them is different issue!)
On a recent large project the authors of systems I wanted to use had placed a lot of the code in .h files. When including their .h files into my own source it added further dependencies to my file. After including the dependencies for their project I ended up with typedef collisions. If they had separated the code and only placed declarations in the .h file it would have been much simpler. I suggest using posix types and only putting declarations into .h files.
I see that a lot of responses advocate separation, primarily for build-time and implementation hiding benefits. Both are definitely pluses, though I'll argue the counter example: Boost.
Most Boost libraries use a .hpp file with no external linking. The reason is that this is often required in the case of templates, when the compiler must know the argument types from the calling routine. So you might not have a choice if you want to stick with the "modern" C++ approach of shunning classes for templates.
As for the comparison part of .cs versus .cpp/.h I think you need to keep in mind the background the lead architect of C#: Anders Hejlsberg. In Delphi you also don't have the distinction of header and module (ignoring include files for this discussion). You simply have two sections in a unit file initialization and implementation.
The other points were already mentioned.