Custom headers higher than standard? - c++

Is it reasonable to put custom headers higher in include section than standard headers?
For example include section in someclass.hpp:
#include "someclass.h"
#include "global.h"
#include <iostream>
#include <string>
Is it best practice? What is the profit if it is?

The reason is that if you forget to include a dependent header in someclass.h, then whatever implementation file includes it as the first header, will get a warning/error of undefined or undeclared type, and whatnot. If you include other headers first, then you could be masking that fact - supposing the included headers define the required types, functions, etc. Example:
my_type.h:
// Supressed include guards, etc
typedef float my_type;
someclass.h:
// Supressed include guards, etc
class SomeClass {
public:
my_type value;
};
someclass.cpp:
#include "my_type.h" // Contains definition for my_type.
#include "someclass.h" // Will compile because my_type is defined.
...
This will compile fine. But imagine you want to use use SomeClass in your program. If you don't include my_type.h before including someclass.h, you'll get a compiler error saying my_type is undefined. Example:
#include "someclass.h"
int main() {
SomeClass obj;
obj.value = 1.0;
}

It is fairly common practice to #include "widget.h" as the first thing in widget.cpp. What this does is ensure that widget.h is self-contained, i.e. does not inadvertently depend on other header files.
Beyond that, I think it's essentially a matter of personal preference.

There are two important observations to be made before delving in the specifics:
When you develop a new header/source pair, it is important to check that the header is self-contained. To do so, the easiest way is to include first in a file.
It is best not to include extraneous things before including a header you do not own, as this could create strange issues in case of conflict of macros or overload of functions.
Therefore, the answer depend if you have unit test or not.
A general rule of thumb is to include headers starting with the Standard Library, then 3rd party headers (including Open Source projects), then your own middleware, utilities, etc... and finally the headers local to this library. It more or less follows the order of dependencies to comply with observation 2.
The only exception I have seen was the one header corresponding to the current source file, which would be included first to make sure it is self-contained (observation 1)... but this only holds if you don't have unit tests, for if you do then the unit test source file is a very good place to check this.

While it is just personal choice, I would prefer to include standard headers first. Few reasons:
Any set of #ifdef..#define would be correctly mapped, rather than standard headers misinterpreting them. This goes for conditional compilation as well as values of some macros, while standard headers are being compiled.
Any change/new function in standard header may conflict with your function, and compiler would emit error in header file, which would be be complicated to solve.
All required standard headers should be placed in one header (preferbly some pre-compiled-header), include that header, and then include your custom header. This would reduce compilation time.

Start with the system headers.
If there are no dependencies between the headers both ways work, but since programming is essentially communication, not with the computer but with other humans, it is important to make it logical and easy to understand. And my opinion is that it is better to start with the system headers.
I base this one of my very first programming courses (in 1984, I think), where we programmed in Lisp and were taught to think like this: you start with the normal Lisp language, and then you create a new language that is more useful for your application by adding some functions and data types. If you for example add dates and the ability to manipulate dates, this new language could be called Lisp-with-dates. Then you could use Lisp-with-dates to create a new language with calendar functionality, which could be called Lisp-with-calendars. Like layers in an onion.
Similarly, you can view C as having a "core" language, without any headers, and then you can for example expand this language into a new, bigger language with I/O functionality by #including stdio.h. You add more and more stuff to the core language by #including more headers. (I am aware that the term "C language" in other contexts refers to the entire standard, with all the standard headers, but bear with me here.) Each new #included header creates a new, bigger language, and an additional layer of the onion.
Now, to me it seems that the standard headers obviously should be the inner part of this onion, and therefore before the custom headers. You can create the language C-with-monsters by adding stuff to C-with-I/O, but the people who created C-with-I/O did not start with C-with-monsters.

any place you include c++ compiler treats it as the same

Related

Is it possible to write header file without include guard, and without multiple definition errors?

Just out of curiosity I wanted to know if is there a way to achieve this.
In C++ we learn that we should avoid using macros. But when we use include guards, we do use at least one macro. So I was wondering if there is a way to write a macro-free program.
It's definitely possible, though it's unimaginably bad practice not to have include guards. It's important to understand what the #include statement actually does: the contents of another file are pasted directly into your source file before it's compiled. An include guard prevents the same code from being pasted again.
Including a file only causes an error if it would be incorrect to type the contents of that file at the position you included it. As an example, you can declare (note: declare, not define) the same function (or class) multiple times in a single compilation unit. If your header file consists only of declarations, you don't need to specify an include guard.
IncludedFile.h
class SomeClassSomewhere;
void SomeExternalFunction(int x, char y);
Main.cpp
#include "IncludedFile.h"
#include "IncludedFile.h"
#include "IncludedFile.h"
int main(int argc, char **argv)
{
return 0;
}
While declaring a function (or class) multiple times is fine, it isn't okay to define the same function (or class) more than once. If there are two or more definitions for a function, the linker doesn't know which one to choose and gives up with a "multiply defined symbols" error.
In C++, it's very common for header files to include class definitions. An include guard prevents the #included file from being pasted into your source file a second time, which means your definitions will only appear once in the compiled code, and the linker won't be confused.
Rather than trying to figure out when you need to use them and when you don't, just always use include guards. Avoiding macros most of the time is a good idea; this is one situation where they aren't evil, and using them here isn't dangerous.
It is definitely doable and I have used some early C++ libraries which followed an already misguided approach from C which essentially required the user of a header to include certain other headers before this. This is based on thoroughly understanding what creates a dependency on what else and to use declarations rather than definitions wherever possible:
Declarations can be repeated multiple times although they are obviously required to be consistent and some entities can't be declared (e.g. enum can only be defined; in C++ 2011 it is possible to also declare enums).
Definitions can't be repeated but are only needed when the definition if really used. For example, using a pointer or a reference to a class doesn't need its definition but only its declaration.
The approach to writing headers would, thus, essentially consist of trying to avoid definitions as much as possible and only use declaration as far as possible: these can be repeated in a header file or corresponding headers can even be included multiple times. The primary need for definitions comes in when you need to derive from a base class: this can't be avoided and essentially means that the user would have to include the header for the base class before using any of the derived classes. The same is true for members defined directly in the class but using the pimpl-idiom the need for member definitions can be pushed to the implementation file.
Although there are a few advantages to this approach it also has a few severe drawbacks. The primary advantage is that it kind of enforces a very thorough separation and dependency management. On the other hand, overly aggressive separation e.g. using the pimpl-idiom for everything also has a negative performance impact. The biggest drawback is that a lot the implementation details are implicitly visible to the user of a header because the respective headers this one depends on need to be included first explicitly. At least, the compiler enforces that you get the order of include files right.
From a usability and dependency point of view I think there is a general consensus that headers are best self-contained and that the use of include guards is the lesser evil.
It is possible to do so if you ensure the same header file is not being included in the same translation unit multiple times.
Also, you could use:
#pragma once
if portability is not your concern.
However, you should avoid using #pragma once over Include Guards because:
It is not standard & hence non portable.
It is less intuitive and not all users might know of it.
It provides no big advantage over the classic and very well known Include Guards.
In short, yes, even without pragmas. Only if you can guarantee that every header file is included only once. However, given how code tends to grow, it becomes increasingly difficult to honour that guarantee as the number of header files increase. This is why not using header guards is considered bad practice.
Pre-processor macros are frowned upon, yes. However, header include guards are a necessary evil because the alternative is so much worse (#pragma once will only work if your compiler supports it, so you lose portability)
With regard to pre-processor macros, use this rule:
If you can come up with an elegant solution that does not involve a macro, then avoid them.
Does the non-portable, non-standard
#pragma once
work sufficiently well for you? Personally, I'd rather use macros for preventing reinclusion, but that's your decision.

Is there any guaranteed dependency of C++ system headers?

For example, in <algorithm>, the function equal_range returns a pair, so can I assume that if I #include <algorithm>, <utility> is #included?
There is never a guaranteed inclusion of header files that other headers depend on. Fortunately, it's common practice (though not certain 100% of the time) that headers are guarded against multiple inclusion -- meaning you can #include them as many times as you wish without causing harm.
You should always include what you need, you cannot rely on all implementations including the same set of headers in another header.
In your example, if a function returns a pair you can be reasonably sure that the pair class is declared, but nothing requires the implementation to include the rest of <utility>.
In fact, it is impossible to implement the standard library using exactly the headers shown in the standard, because there are some circular references. Implementations must split them in smaller parts, and include those sub-headers in the required <> headers.
The GCC team, for example, is working to minimize the amount of inclusions to speed up compile time.
OK, late answer, but I'll add this anyway.
It's about the <iostream> header. In C++98 and C++03 the standard did not guarantee that it would include <istream> and <ostream>, which meant that you were not guaranteed to have available e.g. std::endl. And at least one compiler insisted on being formal about it (in spite of all the non-normative examples in the standard showing the intention)!
Well, I can't remember who pointed it out first, but it was discussed up, down and sideways in [comp.lang.c++]. Several times. And finally James Kanze, bless his soul (well he's not dead yet, in fact he's here on SO), put it to the committee, and it was fixed for C++0x.
So, there's now one header dependency that you can depend on.
Hallelujah!
But in the other direction, C++0x increases the confusion about which headers can put which names in the global namespace and the std namespace. Now any standard library header corresponding to a C library header can freely pollute the global namespace, and be conforming. And so now there's no point in including, say, <cstdio>, but instead now the wise thing to do is to include <stdio.h> and accept a guaranteed global namespace pollution.
Cheers & hth.,
Yeah, you should not assume anything about inclusion of headers. I have been playing around with inclusion of headers for a while, and you know i observed that when it comes to header files like vector and string, you are 'almost' sure that you are including them from somewhere.
Yes but this things are good only when you are just playing around. I would suggest you to always include the headers.
There is no guarantee, but since <algorithm> uses pair internally it is common sense that it should include it. There are ways to make sure that a header file is included only once:
#pragma once http://en.wikipedia.org/wiki/Pragma_once
#ifndef MY_H
#define MY_H
//header code
#endif /* MY_H */
And usually a good library will include all the needed files to compile, and those will be using this kind of mechanism to make sure that they are included only once.
There are sometimes exceptions to this rule especially in private (personal, not standard) libraries where the included header files are placed in the order needed for them to compile. And in that case if you have three includes, probably the second include uses the code from the first and the third from the first and second.
Best approach is to include all that you need to have direct access to the data structures you use.

A basic understanding of C++ header files

I have a theory question rather than an error report.
I'm a rookie C++ programmer, trying to promote that away
Using the VC++ VS2008 compiler
I am often finding myself wondering WHY I want to take some actions in header files.
For example look at this code block:
#include "DrawScene.h"
#include "Camera.h"
#include "Player.h"
#include "Grid.h"
#include "InputHandler.h"
#include "GameState.h"
class Controller
{
public:
private:
public:
Controller();
~Controller(){}
void Update();
private:
};
And the hooked up CPP file , controller.cpp along with it
#include "stdafx.h"
#include "glut.h"
#include "Controller.h"
#include <iostream>
Grid* grid_ptr = new Grid();
InputHandler* inputHandler_ptr = new InputHandler();
DrawScene* drawScene_ptr = new DrawScene();
GameState* gameState_ptr = new GameState();
Controller::Controller()
{
}
void Controller::Update()
{
}
What is a good way to decide which includes go where? So far I've been going with the " whatever works" method but I find it somewhat unprofessional.
Now even though you can say my code has X syntax errors and design flaws, please do, but the focal point I would appreciate that information remains on the use of .h VS .cpp files.
Why is there even such a design? And what are the pits and traps to always be treading lightly around when making any kind of OOP based C++ program?
What sparked this question for me btw was that I wanted to notify the reader of the header file there will be objects stored in the controller but assigning these uninitialized objects seemed impossible without making them static.
Note: I stem from C# --> C++ , might help to know. That's kind of my perspective on code at this point.
Thank you in advance for you efforts!
EDIT: 26/08/2010 18:16
So the build time is the essence of good includes. Is there more to be cautious about?
This is my personal opinion rather than a consensus best practice, but what I recommend is: in a header file, only include those headers that are necessary to make the contents of the header file compile without syntax errors. And if you can use forward declarations rather than nested inclusions, do so.
The reason for this is, in C++ (unlike C#, iiuc) there's no export control. Everything you include from a header will be visible to the includers of the header, which could be a whole lot of junk that users of your interface should not see.
Generally speaking headers should reside in the cpp file. For standard library includes (and possibly 3rd library includes) you can stick them in headers. However headers defined specifically for your project should go in cpp files whenever possible.
The reason for this is compilation time and dependency issues. Any time you change a header file, the compiler will have to recompile every source file that includes it. When you include a header file in another header file, then the compiler has to recompile every cpp file that includes either header file.
This is why forward declaration and the PIMPL (Pointer to IMPLementation, or opaque pointer) pattern are popular. It allows you to shift at least some of the changes/implementation out of the header file. For example:
// header file:
class SomeType;
class AnotherType
{
private:
SomeType *m_pimpl;
};
doesn't require you to include "sometype.h" whereas:
// header file
class AnotherType
{
private:
SomeType m_impl;
};
does. EDIT: Actually, you don't need to include "sometype.h" in the "anothertype.h" if you ALWAYS include "sometype.h" before "anothertype.h" in EVERY cpp file that includes "anothertype.h".
Sometimes it can be difficult to move a header file to the cpp file. At that point you have a decision - is it better to go through the effort of abstracting the code so you can do so, or is it better to just add the include?
Only include headers in another header if absolutely necessary. If the header can go solely in the source file then that's the best place. You can use forward declarations of classes in the header if you are only using pointers and references to them. Your DrawScene, GameState, Grid and InputHandler classes looks like they might fall into this category.
Note that C++ as a language does not care about the distinction between headers and source files. That's just an extremely common system used by developers to maintain their code. The obvious advantage of using headers is to avoid code duplication and helps, to an extent, to enforce the one-definition-rule for classes, templates and inline functions.
Avoid putting too many (read, any unnecessary) #includes in your .h file. Doing so can lead to long build times, as e.g. whenever you change Camera.h you will have changed Controller.h, so anything that includes Controller.h will need to be rebuilt. Even if it is only a comment that has changed.
Use forward declarations if you are only storing pointer members, then add the #includes to the cpp file.
Theoretically, .h files contain just the interface, and .cpp files, the implementation. However, since private members are arguably implementation, and not interface, this is not strictly true, hence the need for forward declarations in order to minimise unnecessary rebuilds.
It is possible, in C++, to include the whole implementation inline in the class definition, file, much as you might with Java, but this really breaks the .h/.cpp interface/implementation rule.
Header files contain declarations of functions, classes, and other objects, whereas cpp files are meant for implementing these previously declared objects.
Header files exist primarily for historical reasons. It's easier to build a C++ compiler if the definitions of all functions, classes, etc to be used by your code are given before you actually call them.
Usually you use cpp for your implemenation. Implementing functions in header files automatically inlines them, so unless these are very small and / or very frequently called, this is usually not what you want.

Is it a good practice to place C++ definitions in header files?

My personal style with C++ has always to put class declarations in an include file, and definitions in a .cpp file, very much like stipulated in Loki's answer to C++ Header Files, Code Separation. Admittedly, part of the reason I like this style probably has to do with all the years I spent coding Modula-2 and Ada, both of which have a similar scheme with specification files and body files.
I have a coworker, much more knowledgeable in C++ than I, who is insisting that all C++ declarations should, where possible, include the definitions right there in the header file. He's not saying this is a valid alternate style, or even a slightly better style, but rather this is the new universally-accepted style that everyone is now using for C++.
I'm not as limber as I used to be, so I'm not really anxious to scrabble up onto this bandwagon of his until I see a few more people up there with him. So how common is this idiom really?
Just to give some structure to the answers: Is it now The Way™, very common, somewhat common, uncommon, or bug-out crazy?
Your coworker is wrong, the common way is and always has been to put code in .cpp files (or whatever extension you like) and declarations in headers.
There is occasionally some merit to putting code in the header, this can allow more clever inlining by the compiler. But at the same time, it can destroy your compile times since all code has to be processed every time it is included by the compiler.
Finally, it is often annoying to have circular object relationships (sometimes desired) when all the code is the headers.
Bottom line, you were right, he is wrong.
EDIT: I have been thinking about your question. There is one case where what he says is true. templates. Many newer "modern" libraries such as boost make heavy use of templates and often are "header only." However, this should only be done when dealing with templates as it is the only way to do it when dealing with them.
EDIT: Some people would like a little more clarification, here's some thoughts on the downsides to writing "header only" code:
If you search around, you will see quite a lot of people trying to find a way to reduce compile times when dealing with boost. For example: How to reduce compilation times with Boost Asio, which is seeing a 14s compile of a single 1K file with boost included. 14s may not seem to be "exploding", but it is certainly a lot longer than typical and can add up quite quickly when dealing with a large project. Header only libraries do affect compile times in a quite measurable way. We just tolerate it because boost is so useful.
Additionally, there are many things which cannot be done in headers only (even boost has libraries you need to link to for certain parts such as threads, filesystem, etc). A Primary example is that you cannot have simple global objects in header only libs (unless you resort to the abomination that is a singleton) as you will run into multiple definition errors. NOTE: C++17's inline variables will make this particular example doable in the future.
As a final point, when using boost as an example of header only code, a huge detail often gets missed.
Boost is library, not user level code. so it doesn't change that often. In user code, if you put everything in headers, every little change will cause you to have to recompile the entire project. That's a monumental waste of time (and is not the case for libraries that don't change from compile to compile). When you split things between header/source and better yet, use forward declarations to reduce includes, you can save hours of recompiling when added up across a day.
The day C++ coders agree on The Way, lambs will lie down with lions, Palestinians will embrace Israelis, and cats and dogs will be allowed to marry.
The separation between .h and .cpp files is mostly arbitrary at this point, a vestige of compiler optimizations long past. To my eye, declarations belong in the header and definitions belong in the implementation file. But, that's just habit, not religion.
Code in headers is generally a bad idea since it forces recompilation of all files that includes the header when you change the actual code rather than the declarations. It will also slow down compilation since you'll need to parse the code in every file that includes the header.
A reason to have code in header files is that it's generally needed for the keyword inline to work properly and when using templates that's being instanced in other cpp files.
What might be informing you coworker is a notion that most C++ code should be templated to allow for maximum usability. And if it's templated, then everything will need to be in a header file, so that client code can see it and instantiate it. If it's good enough for Boost and the STL, it's good enough for us.
I don't agree with this point of view, but it may be where it's coming from.
I think your co-worker is smart and you are also correct.
The useful things I found that putting everything into the headers is that:
No need for writing & sync headers and sources.
The structure is plain and no circular dependencies force the coder to make a "better" structure.
Portable, easy to embedded to a new project.
I do agree with the compiling time problem, but I think we should notice that:
The change of source file are very likely to change the header files which leads to the whole project be recompiled again.
Compiling speed is much faster than before. And if you have a project to be built with a long time and high frequency, it may indicates that your project design has flaws. Seperate the tasks into different projects and module can avoid this problem.
Lastly I just wanna support your co-worker, just in my personal view.
Often I'll put trivial member functions into the header file, to allow them to be inlined. But to put the entire body of code there, just to be consistent with templates? That's plain nuts.
Remember: A foolish consistency is the hobgoblin of little minds.
As Tuomas said, your header should be minimal. To be complete I will expand a bit.
I personally use 4 types of files in my C++ projects:
Public:
Forwarding header: in case of templates etc, this file get the forwarding declarations that will appear in the header.
Header: this file includes the forwarding header, if any, and declare everything that I wish to be public (and defines the classes...)
Private:
Private header: this file is a header reserved for implementation, it includes the header and declares the helper functions / structures (for Pimpl for example or predicates). Skip if unnecessary.
Source file: it includes the private header (or header if no private header) and defines everything (non-template...)
Furthermore, I couple this with another rule: Do not define what you can forward declare. Though of course I am reasonable there (using Pimpl everywhere is quite a hassle).
It means that I prefer a forward declaration over an #include directive in my headers whenever I can get away with them.
Finally, I also use a visibility rule: I limit the scopes of my symbols as much as possible so that they do not pollute the outer scopes.
Putting it altogether:
// example_fwd.hpp
// Here necessary to forward declare the template class,
// you don't want people to declare them in case you wish to add
// another template symbol (with a default) later on
class MyClass;
template <class T> class MyClassT;
// example.hpp
#include "project/example_fwd.hpp"
// Those can't really be skipped
#include <string>
#include <vector>
#include "project/pimpl.hpp"
// Those can be forward declared easily
#include "project/foo_fwd.hpp"
namespace project { class Bar; }
namespace project
{
class MyClass
{
public:
struct Color // Limiting scope of enum
{
enum type { Red, Orange, Green };
};
typedef Color::type Color_t;
public:
MyClass(); // because of pimpl, I need to define the constructor
private:
struct Impl;
pimpl<Impl> mImpl; // I won't describe pimpl here :p
};
template <class T> class MyClassT: public MyClass {};
} // namespace project
// example_impl.hpp (not visible to clients)
#include "project/example.hpp"
#include "project/bar.hpp"
template <class T> void check(MyClass<T> const& c) { }
// example.cpp
#include "example_impl.hpp"
// MyClass definition
The lifesaver here is that most of the times the forward header is useless: only necessary in case of typedef or template and so is the implementation header ;)
To add more fun you can add .ipp files which contain the template implementation (that is being included in .hpp), while .hpp contains the interface.
As apart from templatized code (depending on the project this can be majority or minority of files) there is normal code and here it is better to separate the declarations and definitions. Provide also forward-declarations where needed - this may have effect on the compilation time.
Generally, when writing a new class, I will put all the code in the class, so I don't have to look in another file for it.. After everything is working, I break the body of the methods out into the cpp file, leaving the prototypes in the hpp file.
I personally do this in my header files:
// class-declaration
// inline-method-declarations
I don't like mixing the code for the methods in with the class as I find it a pain to look things up quickly.
I would not put ALL of the methods in the header file. The compiler will (normally) not be able to inline virtual methods and will (likely) only inline small methods without loops (totally depends on the compiler).
Doing the methods in the class is valid... but from a readablilty point of view I don't like it. Putting the methods in the header does mean that, when possible, they will get inlined.
I think that it's absolutely absurd to put ALL of your function definitions into the header file. Why? Because the header file is used as the PUBLIC interface to your class. It's the outside of the "black box".
When you need to look at a class to reference how to use it, you should look at the header file. The header file should give a list of what it can do (commented to describe the details of how to use each function), and it should include a list of the member variables. It SHOULD NOT include HOW each individual function is implemented, because that's a boat load of unnecessary information and only clutters the header file.
If this new way is really The Way, we might have been running into different direction in our projects.
Because we try to avoid all unnecessary things in headers. That includes avoiding header cascade. Code in headers will propably need some other header to be included, which will need another header and so on. If we are forced to use templates, we try avoid littering headers with template stuff too much.
Also we use "opaque pointer"-pattern when applicable.
With these practices we can do faster builds than most of our peers. And yes... changing code or class members will not cause huge rebuilds.
I put all the implementation out of the class definition. I want to have the doxygen comments out of the class definition.
IMHO, He has merit ONLY if he's doing templates and/or metaprogramming. There's plenty of reasons already mentioned that you limit header files to just declarations. They're just that... headers. If you want to include code, you compile it as a library and link it up.
Doesn't that really depends on the complexity of the system, and the in-house conventions?
At the moment I am working on a neural network simulator that is incredibly complex, and the accepted style that I am expected to use is:
Class definitions in classname.h
Class code in classnameCode.h
executable code in classname.cpp
This splits up the user-built simulations from the developer-built base classes, and works best in the situation.
However, I'd be surprised to see people do this in, say, a graphics application, or any other application that's purpose is not to provide users with a code base.
Template code should be in headers only. Apart from that all definitions except inlines should be in .cpp. The best argument for this would be the std library implementations which follow the same rule. You would not disagree the std lib developers would be right regarding this.
I think your co-worker is right as long as he does not enter in the process to write executable code in the header.
The right balance, I think, is to follow the path indicated by GNAT Ada where the .ads file gives a perfectly adequate interface definition of the package for its users and for its childs.
By the way Ted, have you had a look on this forum to the recent question on the Ada binding to the CLIPS library you wrote several years ago and which is no more available (relevant Web pages are now closed). Even if made to an old Clips version, this binding could be a good start example for somebody willing to use the CLIPS inference engine within an Ada 2012 program.

Your preferred C/C++ header policy for big projects? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
When working on a big C/C++ project, do you have some specific rules regarding the #include within source or header files?
For instance, we can imagine to follow one of these two excessive rules:
#include are forbidden in .h files; it is up to each .c file to include all the headers it needs
Each .h file should include all its dependancies, i.e. it should be able to compile alone without any error.
I suppose there is trade-off in between for any project, but what is yours? Do you have more specific rules? Or any link that argues for any of the solutions?
If you include H-files exclusively into C-files, then including a H-file into a C-file might cause compilation to fail. It might fail because you may have to include 20 other H-files upfront, and even worse, you have to include them in the right order. With a real lot of H-files, this system ends up to be an administrative nightmare in the long run. All you wanted to do was including one H-file and you ended up spending two hours to find out which other H-files in which order you will need to include as well.
If a H-file can only be successfully included into a C-file in case another H-file is included first, then the first H-file should include the second one and so on. That way you can simply include every H-file into every C-file you like without having to fear that this may break compilation. That way you only specify your direct dependencies, yet if these dependencies themselves also have dependencies, its up to them to specify those.
On the other hand, don't include H-files into H-files if that isn't necessary. hashtable.h should only include other header files that are required to use your hashtable implementation. If the implementation itself needs hashing.h, then include it in hashtable.c, not in hashtable.h, as only the implementation needs it, not the code that only would like to use the final hashtable.
I think both suggested rules are bad. In my part I always apply:
Include only the header files required to compile a file using only what is defined in this header. This means:
All objects present as reference or pointers only should be forward-declared
Include all headers defining functions or objects used in the header itself.
I would use the rule 2:
All Headers should be self-sufficient, be it by:
not using anything defined elsewhere
forward declaring symbols defined elsewhere
including the headers defining the symbols that can't be forward-declared.
Thus, if you have an empty C/C++ source file, including an header should compile correctly.
Then, in the C/C++ source file, include only what is necessary: If HeaderA forward-declared a symbol defined in HeaderB, and that you use this symbol you'll have to include both... The good news being that if you don't use the forward-declared symbol, then you'll be able to include only HeaderA, and avoid including HeaderB.
Note that playing with templates makes this verification "empty source including your header should compile" somewhat more complicated (and amusing...)
The first rule will fail as soon as there are circular dependencies. So it cannot be applied strictly.
(This can still be made to work but this shifts a whole lot of work from the programmer to the consumer of these libraries which is obviously wrong.)
I'm all in favour of rule 2 (although it might be good to include “forward declaration headers” instead of the real deal, as in <iosfwd> because this reduces compile time). Generally, I believe it's a kind of self-documentation if a header file “declares” what dependencies it has – and what better way to do this than to include the required files?
EDIT:
In the comments, I've been challenged that circular dependencies between headers are a sign of bad design and should be avoided.
That's not correct. In fact, circular dependencies between classes may be unavoidable and aren't a sign of bad design at all. Examples are abundant, let me just mention the Observer pattern which has a circular reference between the observer and the subject.
To resolve the circularity between classes, you have to employ forward declaration because the order of declaration matters in C++. Now, it is completely acceptable to handle this forward declaration in a circular manner to reduce the number of overall files and to centralize code. Admittedly, the following case doesn't merit from this scenario because there's only a single forward declaration. However, I've worked on a library where this has been much more.
// observer.hpp
class Observer; // Forward declaration.
#ifndef MYLIB_OBSERVER_HPP
#define MYLIB_OBSERVER_HPP
#include "subject.hpp"
struct Observer {
virtual ~Observer() = 0;
virtual void Update(Subject* subject) = 0;
};
#endif
// subject.hpp
#include <list>
struct Subject; // Forward declaration.
#ifndef MYLIB_SUBJECT_HPP
#define MYLIB_SUBJECT_HPP
#include "observer.hpp"
struct Subject {
virtual ~Subject() = 0;
void Attach(Observer* observer);
void Detach(Observer* observer);
void Notify();
private:
std::list<Observer*> m_Observers;
};
#endif
A minimal version of 2. .h files include only the header files it specifically requires to compile, using forward declaration and pimpl as much as is practical.
Always have some sort of header guard.
Do not pollute the user's global namespace by putting any using namespace statements in a header.
I'd recommend going with the second option. You often end up in the situation where you want to add somwhing to a header file that suddenly requires another header file. And with the first option, you would have to go through and update lots of C files, sometimes not even under your control. With the second option, you simply update the header file, and the users who don't even need the new functionality you just added needn't even know you did it.
The first alternative (no #includes in headers) is a major no-no for me. I want to freely #include whatever I might need without worrying about manually #includeing its dependencies as well. So, in general, I follow the second rule.
Regarding cyclic dependencies, my personal solution is to structure my projects in terms of modules rather than in terms of classes. Inside a module, all types and functions may have arbitrary dependencies on one another. Across module boundaries, there may not be circular dependencies between modules. For each module, there is a single *.hpp file and a single *.cpp file. This ensures that any forward declarations (necessary for circular dependencies, which can only happen inside a module) in a header are ultimately always resolved inside the same header. There is no need for forward-declaration-only headers whatsoever.
Pt. 1 fails when you would like to have precompiled headers through a certain header; eg. this is what StdAfx.h are for in VisualStudio: you put all common headers there...
This comes down to interface design:
Always pass by reference or pointer. If you aren't going to check the pointer, pass by
reference.
Forward declare as much as possible.
Never use new in a class - create factories to do that for you and pass them to the class.
Never use pre-compiled headers.
In Windows my stdafx only ever includes afx___.h headers - no string, vector or boost libraries.
Rule nr. 1 would require you to list your header files in a very specific order (include files of base classes must go before include files of derived classes, etc), which would easily lead to compilation errors if you get the order wrong.
The trick is, as several others have mentioned, use forward declarations as much as possible, i.e. if references or pointers are used. To minimize build dependencies in this way the pimpl idiom can be useful.
I agree with Mecki, to put it shorter,
for every foo.h in your project include only those headers that are required to make
// foo.c
#include "any header"
// end of foo.c
compile.
(When using precompiled headers, they are allowed, of course - e.g. the #include "stdafx.h" in MSVC)
Personally I do it this way:
1 Perfer forward declare to include other .h files in a .h file. If something could be used as pointer/reference in that .h files or class, forward declare is possible without compile error. This could make headers less include dependencies(save compile time? not sure:( ).
2 Make .h files simple or specific. e.g. it is bad to define all constances in a file called CONST.h, it is better to divid them into multiple ones like CONST_NETWORK.h, CONST_DB.h. So to use one constance of DB, it needn't to include other information about network.
3 Don't put implementation in headers. Headers are used to quick review public things for other people; when implementing them, don't pollute declaration with detail for others.