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.
Related
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?
In my current project. A lot of my .cpp and .h files have plenty of includes in them such as 6 or 7 of headers declared in the following manner.
#ifndef A_Header
#include "a.h"
#endif
#ifndef B_Header
#include "b.h"
#endif
I wanted to know would it make sense if I wrapped all of these headers (used in the project) in a single header and then declare that header in each source file as such
#ifndef Wrapper_Header
#include "wrapper.h" /*This would contain a collection of all headers*/
#endif
Any suggestions and drawbacks of this plan that I am not anticipating?
That's totally bizarre.
Every header should contain a header guard:
#ifndef THIS_HEADER
#define THIS_HEADER
/* contents of the header */
#endif
This goes inside the header, not in the including .cpp file. The compiler detects the header guard and avoids re-reading all the text when it's included again. This can save seconds of compilation time.
If your headers have that, then the guards in the .cpp file are extraneous and you should remove them. 6 or 7 headers isn't a lot, but that silly boilerplate does sure add up.
Never wrap your headers, always be explicit, make it clear what is included, and do not include what you do not need.
Potatoswatter is correct
But I like to add use "forward declaration".
I am sure you can google it.
I'm new to programming and the topic of header files is sort of bogging me down after I started using a lot of them. In addition to that I'm trying to use precompiled headers. I'm also using the SFML library so I have those headers that also have to be included.
Right now I have stdafx.h, main.cpp, then classes A, B, C, and D contained within A.h, A.cpp, B.h, B.cpp, C.h, C.cpp, D.h, and D.cpp.
What order would I go about including the headers in all files if
all classes contain an instance of an SFML class
class D contains an instance of class A and class C
class C contains an instance of class B
My code: (note: all headers have header guards)
stdafx.h:
#include <SFML/Graphics.hpp>
#include <iostream>
A.h
#include "stdafx.h"
class A
{
//sfml class
};
A.cpp
#include "stdafx.h"
#include "A.h"
B.h
#include "stdafx.h"
class B
{
//sfml class
};
B.cpp
#include "stdafx.h"
#include "B.h"
C.h
#include "B.h"
class C: public B
{
};
C.cpp
#include "stdafx.h"
#include "C.h"
D.h
#include "A.h"
#include "C.h"
class D
{
A a;
C C; // if left uncommented I recieve a '1 unresolved externals' error
//sfml class
}
D.cpp
#include "stdafx.h"
#include "D.h"
main.cpp
#include "stdafx.h"
#include "D.h"
My philosophy is that in well-written code, header files should include all other header files that they depend on. My reasoning is that it should not be possible to include a header file and get a compiler error for doing so. Therefore, each header file should (after the #ifdef or #pragma once include guard) include all other headers it depends on.
In order to informally test that you've remembered to include the right headers in your header files, *.cpp files should #include the minimum set of header files that should work. Therefore, if there are separate header files for A, B, C and D, and your cpp file uses class D, then it should only include D.h. No compiler errors should result, because D.h #includes A.h and C.h, C.h includes B.h, and A.h and B.h include the SFML header (whatever that is). C.h and D.h can include the SFML header if it seems appropriate, but it's not really necessary, if you can be sure that the dependencies (B.h and A.h) already included it.
The way Visual C++ does "precompiled headers" screws up this logic, however. It requires you to include "StdAfx.h" as the very first header file, which causes many developers to simply put all #includes for the entire project in StdAfx.h, and not to use #include in any of the other header files. I don't recommend this. Or, they will put all external dependencies in StdAfx.h (e.g. windows.h, boost headers) and #include the local dependencies elsewhere so that changing a single header file does not necessarily cause the entire project to rebuild.
The way I write my code, most of my CPP files include StdAfx.h, and the corresponding .H file. So A.cpp includes StdAfx.h and A.h, B.cpp includes StdAfx.h and B.h, and so forth. The only other #includes placed in a cpp file are "internal" dependencies that are not exposed by the header file. For example, if class A calls printf(), then A.cpp (not A.h) would #include <stdio.h>, because A.h does not depend on stdio.h.
If you follow these rules then the order that you #include headers does not matter (unless you use precompiled headers: then the precompiled header comes first in each cpp file, but does not need to be included from header files).
Take a look at a similar question to learn a good approach to authoring headers.
In short, you want to define each header inside a definition guard that prevents headers from being included more then once during compilation. With those in place, for each .h and .cpp file, just include the headers needed to resolve any declarations. The pre-processor and compiler will take care of the rest.
C inherits class B. So, it should see the identifier B. So, include B.h here -
#include "B.h" // Newly added
// Or you can forward declare class B ;
class C: public B
{
};
D has objects of class A, B. So, include headers of A, B in the "D.h" itself.
class D
{
A a; // Should see the definition of class A
C c; // Should see the definition of class B
//sfml class
}
D.cpp
#include "A.h"
#include "C.h"
#include "D.h" // Notice that A.h and C.h should definitely placed before
Note that every header needs to be included in it's corresponding source file. Think of each source file independently and see whether what ever is used is earlier defined or not in the source file.
A.h should include SFML
A.cpp should include A.h
D.h should include SFML, A.h and C.h
D.cpp should include D.h
main.cpp should include whichever of A, B, C, D and SFML that it uses directly.
Generally in a .cpp file I don't include any headers that you know must be included by its corresponding .h because they contain the definitions of data members of classes defined in that .h. Hence, in my code D.cpp would not include A.h. That's just me, though, you might prefer to include it anyway just to remind you that the .cpp file (presumably) uses it.
This leaves stdafx - where you need this depends what uses the things in it. Probably it's needed everywhere, and MSVC doesn't process (or processes but discards?) anything before #include "stdafx.h" in a source file, so it should be the first thing in each .cpp file and appear nowhere else.
All header files should have multiple-include guards.
You could add SFML (or anything else you feel like) to stdafx.h, in which case you might as well remove those includes from everywhere else.
Once you've done this, it no longer matters what order you include the headers in each file. So you can do what you like, but I recommend Google's C++ style guide on the subject (click on the arrow thing), adjusted to account for stdafx.h.
Depends on dependencies. Unlike C# and other similar languages, C++ does things in the order it is written, so there may be an issue. If you do have a problem with the order then it will not compile.
When coding in either C or C++, where should I have the #include's?
callback.h:
#ifndef _CALLBACK_H_
#define _CALLBACK_H_
#include <sndfile.h>
#include "main.h"
void on_button_apply_clicked(GtkButton* button, struct user_data_s* data);
void on_button_cancel_clicked(GtkButton* button, struct user_data_s* data);
#endif
callback.c:
#include <stdlib.h>
#include <math.h>
#include "config.h"
#include "callback.h"
#include "play.h"
void on_button_apply_clicked(GtkButton* button, struct user_data_s* data) {
gint page;
page = gtk_notebook_get_current_page(GTK_NOTEBOOK(data->notebook));
...
Should all includes be in either the .h or .c / .cpp, or both like I have done here?
Put as much as you can in the .c and as little as possible in the .h. The includes in the .c are only included when that one file is compiled, but the includes for the .h have to be included by every file that uses it.
The only time you should include a header within another .h file is if you need to access a type definition in that header; for example:
#ifndef MY_HEADER_H
#define MY_HEADER_H
#include <stdio.h>
void doStuffWith(FILE *f); // need the definition of FILE from stdio.h
#endif
If header A depends on header B such as the example above, then header A should include header B directly. Do NOT try to order your includes in the .c file to satisfy dependencies (that is, including header B before header A); that is a big ol' pile of heartburn waiting to happen. I mean it. I've been in that movie several times, and it always ended with Tokyo in flames.
Yes, this can result in files being included multiple times, but if they have proper include guards set up to protect against multiple declaration/definition errors, then a few extra seconds of build time isn't worth worrying about. Trying to manage dependencies manually is a pain in the ass.
Of course, you shouldn't be including files where you don't need to.
Put as many includes in your cpp as possible and only the ones that are needed by the hpp file in the hpp. I believe this will help to speed up compilation, as hpp files will be cross-referenced less.
Also consider using forward declarations in your hpp file to further reduce the include dependency chain.
If I #include <callback.h>, I don't want to have to #include lots of other header files to get my code to compile. In callback.h you should include everything needed to compile against it. But nothing more.
Consider whether using forward declarations in your header file (such as class GtkButton;) will suffice, allowing you to reduce the number of #include directives in the header (and, in turn, my compilation time and complexity).
I propose to simply include an All.h in the project that includes all the headers needed, and every other .h file calls All.h and every .c/.cpp file only includes its own header.
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++: