Custom header files and include libraries [C++] - c++

If I create a header like this:
#ifndef _MY_HEADER_H
#define _MY_HEADER_H
#include <iostream>
void foo();
#endif
With it's correspondent .cpp file, do I need to include iostream in the main.cpp file?

To answer you question: No you don't need to include it (again).
But it is good practice, to include in the header only the stuff that is required for the header to work. So if your foo() method requires iostream, you should include it. If you create a class that uses only pointers or references to other classes you should prefer forward declarations over inclusion of the full-fledged header of the respective classes.

It is not necessary to include it again in main.cpp, as in main.cpp version if you include the .h version of the same ,the inclusion will automatically be available in compilation, why write an extra redundant line?

Related

Including a library in both the header file and the cpp file

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.

If I need to include another header in my header and I plan to use it in my CPP file, should I include it there as well for readability?

Right so I'll try to explain my question as best as I can. Basically in one of my header files I need to use a class, obviously to do this I will have to include that class' header in the current one. I was just thinking, since I'm planning to create a new instance of this class later on down the line, should I also include it in the .cpp file to help with readability? I know that I don't have to, but would it make sense to do that? Or am I just being insane?
Example A, header file:
include "APIManager.h"
class Environment
{
public:
static void Initialize();
private:
APIManager apiManager;
};
Example A, source file:
include "Environment.h"
// Should I include "APIManager.h" here too?
void Environment::Initialize()
{
}
Tried looking around here for it, but I'm unsure of how to phrase it, so apologies if this has already been asked.
Also, in general should you be including the header files that the class's source needs in that class's header? Thanks.
If the source file is Environment.cpp, where you are implementing what you declared in Environment.h, then no, you should not reinclude it.
If on the other hand, the source file is SomeOtherFile.cpp where you are simply using the declarations from Environment.h, and you are going to use the declarations from APIManager.h separately and independently of their usage as part of Environment.h, then yes, you should. You wouldn't want a future change which removes #include <Environment.h> from SomeOtherFile.cpp to break it unexpectedly.
In other words, if SomeOtherFile.cpp has a direct dependence on APIManager.h, then that dependence should be directly expressed via a #include.
This is basically a style question, but:
No you shouldn't include it in the cpp and the header. It's overly verbose and no one does it.
I would not, except if the #include "APIManager.h" might not be in header.
<string> might be included in <iostream>, but you should include <string> anyway even if your library include include it and you use <iostream>
Include headers where they're needed.
You should include them in a header file if your class definition includes objects defined in the header you're including. If you're only using the contents of a header in the cpp, then include it in the cpp.
Never include the same external header in both file.h and file.cpp if file.cpp also includes file.h.

Should re-include stuff thats already in the project scope precompiled header?

I have a precompiled header stdafx.h which is used in all source files in my project. Thus all headers in the stdafx.h are available in all code files in the project.
What I'm unsure about is whether or not to re-include stuff thats already in the precompiled header. What do you guys think?
e.g.
stdafx.h
#pragma once
#include <memory>
my_class.h
#pragma once
#include <memory> // Re-include or not that's the question. Best practice?
struct my_class
{
};
typedef std::shared_ptr<my_class> my_class_ptr;
main.cpp
#include "stdafx.h"
#include "my_class.h"
int main()
{
}
I would include it so that the header could be reused in a project which has different stdafx.h Another way of stating this is each header should contain all the declarations (preferably forward ones) it needs on its own
There will not be any performance hit as the contents of the header will not be processed due to internal header guard (or for VS the #pragma:once in the header file.
In a header you should include everything, that is necessary for that header to be used separately. If you use std::shared_ptr in a header and that template comes from memory header, include memory header.
When you design a header your goal should be to make it complete, so that when someone includes it, he/she doesn't get errors caused by unresolved references. Don't worry that some headers might be included repeatedly. There are other mechanisms to protect against that.
BTW, use those mechanisms (like #pragmaor #ifndef/#define) in your header too.
The best practice would be to use forward declarations as much as possible. Having unnecessary includes might increase compilation time. Always include headers in a file if the implementation uses it even though it was included in a previously included file. This way, if some day you need to remove the header inclusion from the previous file, you will not cause errors in this file and the file won't need any modification.

C++ Header Guard issues

I am making a small C++ framework, which contains many .h and .cpp.
I have created a general include which include all my .h file such as:
framework.h
#include "A.h"
#include "B.h"
#include "C.h"
each .h header are protected with include guard such as
#ifndef A_HEADER
#define A_HEADER
...
#endif
The issues is, I would like to be able to include "framework.h" inside all the sub .h such as, but it cause lots of compiler error:
#ifndef A_HEADER
#define A_HEADER
#include "framework.h"
...
#endif
If instead I use the real header file for each sub header, and the framework.h for what ever use my framework it works fine..
I would just like to include the main header inside all my sub .h so I dont need to include all the dependency everytime.
Thanks :)
Basically what your doing is #include "A.h" in framework.h and #include "framework.h" in A.h. This causes cyclic dependency of the header files and you will get errors such as undefined class A. To solve this, use forward declarations in header file and #include only in corresponding cpp file. If that is not possible then I don't see any other option other than including individual header files.
Just protect the main header with include guards too:
#ifndef FRAMEWORK_H
# define FRAMEWORK_H
# include <A.h>
# include <B.h>
# include <C.h>
#endif
That will prevent recursive inclusion.
You should not including the main header file inside the sub-header files. It should be used to make user's life easier, not yours.
Instead do following:
1) Make forward definitions of all you need in the related sub-header files.
2) Include only needed sub-header files inside CPP files.
3) When using your framework inside an application code (for example), then you could include the main framework header file.
i would recommend using #pragma once, and placing that at the top of all of your header files (framework.h, A.h, B.h, and C.h).
Although, if you'd rather, I think you could fix your problem by simply putting an include guard in framework.h as well.
I guess you have a dependency between - say B and C such that B depends on C, but in framework.h C is included after B.
Circular includes are generally a bad idea in C++. While having header guards will prevent the preprocessor from going into infinite loop (or throwing an error because of this), you will get unexpected compiler errors, because at some point a header file will not be included when if you think it is.
You should include A.h, B.h and C.h from framework.h, and in A.h, do not include framework.h, just forward declare the classes you use from it. Or do it the other way around: include framework.h from A.h, B.h and C.h, and forward declare classes in framework.h. And, of course, put every code that would require any more detailed declarations than for example class A to the .cpp files.

Is there a standard #include convention for C++?

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++: