I have a quick question regarding header files, include statements, and good coding style. Suppose I have 2 classes with associated source and header files, and then a final source file where main() is located.
Within Foo.hpp I have the following statements:
#include <string>
#include <iostream>
#include <exception>
Now withing Bar.hpp I have the following statements:
#include "Foo.hpp"
#include <string>
And finally withing Myprogram.cpp I have the following statements:
#include "Bar.hpp"
#include <string>
#include <iostream>
#include <exception>
I know the include statements in <> in Myprogram.cpp and Bar.hpp aren't necessary for the program to compile and function, but what is the best practice or right way of doing things? Is there any reason to not explicitly include the necessary header files in each file?
You should include all necessary files in every file that needs them. If MyProgram.cpp needs string, include it, instead of relying on it being included by Bar.hpp. There's no guarantee 2 weeks from now Bar.hpp will still include it, and then you'll be left with compiler errors.
Note the necessary - i.e. make sure you actually need an include, when a forward declaration or even leaving it out completely will do.
Also, note that some system headers might include others - apart from a few exceptions, there's no requirement. So if you need both <iostream> and <string> include both, even if you can compile only with one of them.
The order in which the includes appear (system includes vs user includes) is up to the coding standard you follow - consistency is more important than the choice itself.
Include all you need in every file, but do not include any file that you do not need. Normally, it is the job of the included file to make sure it is not included twice, using precompiler flags, etc...
For example if is needed by Foo.cpp, but not by Foo.h, include it in Foo.cpp not in Foo.h. If required in both, include in both.
Tangentially, as a best practice, never use using directives in a header file. If you need you can use using directives in implementation files (.cpp).
Related
Say I have a file, player.h, and in player.h I have included the following:
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
Would I need to include these again in player.cpp, where I flesh out the functions declared in the header file? If I don't, do I need to include them when I run main.cpp, which calls the functions from my various .cpp's and .h's
School never really told me whether or not to do it, so I've always included everything across the board. If it's unnecessary is there any noticeable difference between including everything multiple times and not doing so?
An include preprocessor directive tells the preprocessor to replace it with the contents of the file. Hence when you have
// some_header.h
#include <foo>
and
// some_source.cpp
#include <some_header.h>
then if you compile source.cpp, what the compiler gets to see after the preprocessing step is this:
// some_source.cpp
... contents of foo ...
That is: The #include <some_header.h> is replaced by contents of that header and #include <foo> is replaced by contents of foo.
No, you do not need to include headers twice. Though as headers should have include guards it also won't hurt. The recommonendation is: Include what you use (but not more).
I am new to C++. I have seen code that includes a library file (string as an example) in both the header and cpp file. Will this cause duplicate code if #ifndef is not used? or is the preprocessor smart enough to ignore it. Is it normal to include the same library in both files?
test.h
#include <string>
.
.
.
test.cpp
#include <string>
#include "test.h"
.
.
.
Is it normal to include the same library in both files?
Yes. It is normal to include a header into multiple files.
Whenever you use a declaration from a header, you should include that header. If you use std::string in test.h, then you should include <string> in test.h. If you use std::string in test.cpp, then you should in include <string> in test.cpp. Whether <string> happens to be included in one of the headers included by test.cpp is irrelevant and is something that shouldn't be relied upon.
Will this cause duplicate code if #ifndef is not used?
If a header doesn't have a header guard, then including it multiple times will indeed cause its content to be duplicated, yes.
or is the preprocessor smart enough to ignore it.
The preprocessor doesn't ignore any includes. Each include will be processed. A preprocessor may be smart enough to optimise inclusion of a header that it knows would be empty due to an include guard.
All C++ standard library header files have ifndef guards. It is safe to include them in multiple files.
The rule of thumb is to include the file everywhere where its definitions are needed. This means if you're using std::string in both h and cpp files, include <string> in both.
For any of your own header files, you should always use ifndef guards for the same purpose.
I am currently abstracting OpenGL in C++ and I was just wondering if a certain practice I am doing is considered clean and efficient or the complete opposite. I have a header file which is included in close to almost every single header file for the abstraction called "pd.h" and in this file I include everything my program needs as such:
#pragma once
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
Is this a very unclean and inefficient way for structuring my code? Because this is just how I've taught myself to do things and for some reason looking at it now it looks abit dodgy, and if it is not a good practice could someone explain why I shouldn't be doing this?
This is something that works, but it has two drawbacks, assuming you use a build system which compiles each .cpp file into its own .o file and only later links these into the executable.
Each time your pd.h file changes, all including files need to be recompiled. This means that your whole project has to be recompiled when you change this header. If you know that this file will not change often, then this is not a big drawback for a small project.
Build time is increased for each .cpp file because all those header files need to be processed, even though they are not needed. Compilers can precompile headers (check out for VS), though this is not part of the ISO C++ standard. Not including headers that are not used is an approach which is simpler to use and scales better.
The size of the executable will not change, nor the performance of the resulting application. Just the compilation time is increased.
So instead have the include only when you really need it. Is it sufficient to have it in the .cpp file? Do so. Only if it needs to be included in a header file, do so.
Sometimes you can get away with a forward declaration only. This is the case when the compiler does not need to know the size of the object because you are only defining a pointer to it in the current header.
When you use something, this is the order that I would try:
Include that header in the source file only
Use a forward declaration in the header file (might need to keep the include in the source file)
Include that header in the header file
There is a header iosfwd which has forward declarations for the iostream header, which can be helpful if you just provide overloads for operator<< for your class. These only take std::ostream & and therefore the compiler does not need to know the size.
I got a comprehension issue about precompiled headers, and the usage of the #include directive.
So I got my "stdafx.h" here and include there for example vector, iostream and string. The associated "stdafx.cpp" only includes the "stdafx.h", that's clear.
So if I design my own header file that uses for example "code" that's in vector or iostream, I have to include the header file because the compiler doesn't know the declarations at that time. So why are some posts here (include stdafx.h in header or source file?) saying, it's not good to include the "stdafx.h" in other header files even if this file includes the needed declarations of e.g. vectors? So basically it wouldn't matter to include directly a vector or the precompiled header file, both do the same thing.
I know of course, that I don't have to include a header file in another header file if the associated source file includes the needed header file, because the declarations are known at that time. Well, that only works if the header file is included somewhere.
So my question is: Should I avoid including the precompiled header file in any source file and why? And I am a bit confused, because I'm reading contradictory expressions on the web that I shouldn't include anything in header files anyway, or is it O.K. to include in header files?
So what's right now?
This will be a bit of a blanket statement with intent. The typical setup for PCH in a Visual Studio project follows this general design, and is worth reviewing. That said:
Design your header files as if there is no PCH master-header.
Never build include-order dependencies in your headers that you expect the including source files will fulfill prior to your headers.
The PCH master-header notwithstanding (I'll get to that in a moment), always include your custom headers before standard headers in your source files. This makes your custom header is more likely to be properly defined and not reliant on the including source file's previous inclusion of some standard header file.
Always set up appropriate include guards or pragmas to avoid multiple inclusion. They're critical for this to work correctly.
The PCH master-header is not to be included in your header files. When designing your headers, do so with the intent that everything needed (and only that which is needed) by the header to compile is included. If an including source file needs additional includes for its implementation, it can pull them in as needed after your header.
The following is an example of how I would setup a project that uses multiple standard headers in both the .h and .cpp files.
myobject.h
#ifndef MYAPP_MYOBJECT_H
#define MYAPP_MYOBJECT_H
// we're using std::map and std::string here, so..
#include <map>
#include <string>
class MyObject
{
// some code
private:
std::map<std::string, unsigned int> mymap;
};
#endif
Note the above header should compile in whatever .cpp it is included, with or without PCH being used. On to the source file...
myobject.cpp
// apart from myobject.h, we also need some other standard stuff...
#include "myobject.h"
#include <iostream>
#include <fstream>
#include <algorithm>
#include <numeric>
// code, etc...
Note myobject.h does not expect you to include something it relies on. It isn't using <iostream> or <algorithm>, etc. in the header; we're using it here.
That is a typical setup with no PCH. Now we add the PCH master
Adding the PCH Master Header
So how do we set up the PCH master-header to turbo-charge this thing? For the sake of this answer, I'm only dealing with pulling in standard headers and 3rd-party library headers that will not undergo change with the project development. You're not going to be editing <map> or <iostream> (and if you are, get your head examined). Anyway...
See this answer for how a PCH is typically configured in Visual Studio. It shows how one file (usually stdafx.cpp) is responsible for generating the PCH, the rest of your source files then use said-PCH by including stdafx.h.
Decide what goes in the PCH. As a general rule, that is how your PCH should be configured. Put non-volatile stuff in there, and leave the rest for the regular source includes. We're using a number of system headers, and those are going to be our choices for our PCH master.
Ensure each source file participating in the PCH turbo-mode is including the PCH master-header first, as described in the linked answer from (1).
So, first, the PCH master header:
stdafx.h
#ifndef MYAPP_STDAFX_H
#define MYAPP_STDAFX_H
// MS has other stuff here. keep what is needed
#include <algorithm>
#include <numeric>
#include <iostream>
#include <fstream>
#include <map>
#include <string>
#endif
Finally, the source files configured to use this then do this. The minimal change needed is:
UPDATED: myobject.cpp
#include "stdafx.h" // <=== only addition
#include "myobject.h"
#include <iostream>
#include <fstream>
#include <algorithm>
#include <numeric>
// code, etc...
Note I said minimal. In reality, none of those standard headers need appear in the .cpp anymore, as the PCH master is pulling them in. In other words, you can do this:
UPDATED: myobject.cpp
#include "stdafx.h"
#include "myobject.h"
// code, etc...
Whether you choose to or not is up to you. I prefer to keep them. Yes, it can lengthen the preprocessor phase for the source file as it pulls in the headers, runs into the include-guards, and throws everything away until the final #endif. If your platform supports #pragma once (and VS does) that becomes a near no-op.
But make no mistake: The most important part of all of this is the header myobject.h was not changed at all, and does not include, or know about, the PCH master header. It shouldn't have to, and should not be built so it has to.
Precompiled headers are a method to shorten the build time. The idea is that the compiler could "precompile" declarations and definitions in the header and not have to parse them again.
With the speed of todays computers, the precompilation is only significant for huge projects. These are projects with a minimum of over 50k lines of code. The definition of "signification" is usually tens of minutes to build.
There are many issues surrounding Microsoft's stdafx.h. In my experience, the effort and time spent with discovering and resolving the issues, makes this feature more of a hassle for smaller project sizes. I have my build set up so most of the time, I am compiling only a few files; the files that don't change are not compiled. Thus, I don't see any huge impact or benefit to the precompiled header.
When using the precompiled header feature, every .cpp file must begin by including the stdafx.h header. If it does not, a compiler error results. So there is no point in putting the include in some header file. That header file cannot be included unless the stdafx.h has already been included first.
This is a rather basic question, but it's one that's bugged me for awhile.
My project has a bunch of .cpp (Implementation) and .hpp (Definition) files.
I find that as I add additional classes and more class inter-dependencies, I have to #include other header files. After a week or two, I end up with #include directives in lots of places. Later, I'll try removing some of the #includes and discover that everything still works because some OTHER included class is also #including what I just removed.
Is there a simple, easy rule for putting in #includes that will stop this ugly mess from happening in the first place? What is the best practice?
For example, I've worked on projects where the Implementation .cpp file ONLY includes the corresponding Definition .hpp file, and nothing else. If there are any other .hpp files that need to be used by the Implementation .cpp, they are all referenced by the Definition .hpp file.
Some best practices:
Every .cpp or .C file includes all headers it needs and does not rely on headers including other related headers
Every .hpp or .h file includes all its dependencies and does not rely on the included headers including other related headers
Every header is wrapped with:
#ifndef HEADER_XXX_INCLUDED
#define HEADER_XXX_INCLUDED
...
#endif /* HEADER_XXX_INCLUDED */
Headers do not include each others in cycles
Often: there is a single "project-wide header file" like "config.h" or ".h" which is always included first by any .cpp or .C file. Typically this has platform related configuration data, project-wide constants and macros etc.
These are not necessarily "best practice", but rules which I usually follow also:
Project-specific headers are included as #include "..." and before the system-wide headers, which are included as #include <...>
Project-specific headers are included in alphabetical order as a way to ensure that there is no accidental, hidden requirement on which order they are included. As every header should include its dependents and the headers should be protected against multiple inclusion, you should be able to include them in any order you wish.
Check out John Lakos's Large-Scale C++ Software Design. Here's what I follow (written as an example):
Interface
// foo.h
// 1) standard include guards. DO NOT prefix with underscores.
#ifndef PROJECT_FOO_H
#define PROJECT_FOO_H
// 2) include all dependencies necessary for compilation
#include <vector>
// 3) prefer forward declaration to #include
class Bar;
class Baz;
#include <iosfwd> // this STL way to forward-declare istream, ostream
class Foo { ... };
#endif
Implementation
// foo.cxx
// 1) precompiled header, if your build environment supports it
#include "stdafx.h"
// 2) always include your own header file first
#include "foo.h"
// 3) include other project-local dependencies
#include "bar.h"
#include "baz.h"
// 4) include third-party dependencies
#include <mysql.h>
#include <dlfcn.h>
#include <boost/lexical_cast.hpp>
#include <iostream>
Precompiled Header
// stdafx.h
// 1) make this easy to disable, for testing
#ifdef USE_PCH
// 2) include all third-party dendencies. Do not reference any project-local headers.
#include <mysql.h>
#include <dlfcn.h>
#include <boost/lexical_cast.hpp>
#include <iosfwd>
#include <iostream>
#include <vector>
#endif
I always use the principle of least coupling. I only include a file if the current file actually needs it; if I can get away with a forward declaration instead of a full definition, I'll use that instead. My .cpp files always have a pile of #includes at the top.
Bar.h:
class Foo;
class Bar
{
Foo * m_foo;
};
Bar.cpp:
#include "Foo.h"
#include "Bar.h"
Use only the minimum amount of includes needed. Useless including slows down compiling.
Also, you don't have to include a header if you just need to pointer to a class. In this case you can just use a forward declaration like:
class BogoFactory;
edit: Just to make it clear. When I said minimum amount, I didn't mean building include chains like:
a.h
#include "b.h"
b.h
#include "c.h"
If a.h needs c.h, it needs to be included in a.h of course to prevent maintenance problems.
There are several problems with the #include model used in C/C++, the main one being that it doesn't express the actual dependency graph. Instead it just concatenates a bunch of definitions in a certain order, often resulting in definitions coming in a different order in each source file.
In general, the include file hierarchy of your software is something you need to know in the same way as you know your datastructures; you have to know which files are included from where. Read your source code, know which files are high up in the hierarchy so you can avoid accidentally adding an include so that it will be included "from everywhere". Think hard when you add a new include: do I really need to include this here? What other files will be drawn in when I do this?
Two conventions (apart from those already mentioned) which can help out:
One class == one source file + one header file, consistently named. Class A goes in A.cpp and A.h. Code templates and snippets are good here to reduce the amount of typing needed to declare each class in a separate file.
Use the Impl-pattern to avoid exposing internal members in a header file. The impl pattern means putting all internal members in a struct defined in the .cpp file, and just have a private pointer with a forward declaration in the class. This means that the header file will only need to include those headerfiles needed for its public interface, and any definitions needed for its internal members will be kept out of the headerfile.
Building on what antti.huima said:
Let's say you have classes A, B, and C. A depends on (includes) B, and both A and B depend on C. One day you discover you no longer need to include C in A, because B does it for you, and so you remove that #include statement.
Now what happens if at some point in the future you update B to no longer use C? All of a sudden A is broken for no good reason.
In A.cpp, always include A.h first, to ensure that A.h has no additional dependencies.
Include all local (same module) files before all project files before all system files, again to ensure that nothing depends on pre-included system files.
Use forward declarations as much as possible.
Use #indef/#define/#endif pattern
If a header is included in A.h, you don't need to include it in A.cpp. Any other headers A.cpp needs must be explicitly included, even if they happen to be provided by other .h files.
Organizing code files in C and C++: