Let's pretend my .h file for the creation of precompiled headers looks like the following:
stdafx.h
#include "A.h" //an external library
.. and "A.h" includes a bunch of other headers:
A.h
#include "B.h" //other headers from an external library included by "A.h"
#include "C.h"
//...
Will precompiled headers be also generated for "B.h" and "C.h" (and the header files that these two files include, and so on...), or do I have to include "B.h" and "C.h" in my "stdafx.h" also?
Yes, the precompiled state will include B and C.
Precompilation works by running the compiler as far as the end of stdafx.h and dumping its state to the disk, then restoring that state before compiling the body of each source file. Everything the compiler sees when compiling stdafx.h goes into that state.
(Put it another way: the process of compiling stdafx.h is exactly the same regardless of whether you're generating the precompilation state or just compiling a source file "normally" - it's just that in the precompilation case the compiler stops at the end of the file. It couldn't treat B and C any differently even if it wanted to.)
Related
I have a very basic project in VS2012 using precompiled headers. I know that I'm supposed to add all "common" includes to stdafx.h and that I need to include this in each .cpp file. Thus, the basic setup looks like this:
Foo.h:
#ifndef FOO_H
#define FOO_H
class Foo {
public:
Foo();
~Foo();
void do(string str);
};
#endif
Foo.c:
#include "stdafx.h"
#include "Foo.h"
void Foo::do(string str) {}
in stdafx.h:
#include <string>
using namespace std;
Without precompiled headers, I'd put #include <string> into foo.h, since it has to know about the declaration of string. But how this foo.h know about string in this setup? (Note that stdafx.h is only included in the .cpp files).
Note: I have a working example that uses precompiled headers; the question is about how this works.
This is because the compiler processes headers in the order in which they appear in the main compilation unit.
Because the .cpp file included <string> (indirectly via "stdafx.h"), the contents of <string> are known to the compiler, and can be used by code that follows, even code pulled in from header files.
It is fragile though, because including your header file without first including <string> will cause errors.
You can look on the pre-compiled headers as a kind of cache for header files. The compiler analyzes a set of headers when it first encounters it (usually when compiling stdafx.cpp), compiles them, and then has the results ready for any module that needs them.
What is the difference between doing a #include in a .h file and in a .c file?
For example, I have the file a.h and a.c which have the class A. I use class A in class B (b.h, b.c). What is the difference between doing an include:
#include "a.h"
in b.h vs b.c?
Usually, the class definition is typically in your .h file, and the implementation is in your .c(pp) file.
One advantage of doing #include "a.h" in your b.c file, rather than in your b.h file, is that whenever a.h changes, not only b.c but also any other file that includes b.h will have be recompiled.
Also, you're kind of unnecessary exposing implementation details of B to anyone using b.h. The idea is that b.h should not contain additional info that is of no interest to someone using class B (not because it's secret, but because people don't care and you don't want to bother them with it).
There's no need to force anyone including b.h, to indirectly include a dozen of other .h files as well (because they're #included in b.h), just because you happen to use that stuff in b.c. Avoid clutter.
So if possible, it's best to #include "a.h" in b.c !
But this is not always possible. If you're just using A inside b.c, and there are no references to A in b.h, then it's OK. Also, if b.h only contains pointers to A (i.e. as members, function arguments or return values) but no 'type dependent' references, you could also put just this in b.h:
class A;
And still keep #include "a.h" in your b.c. But if there are more references or dependencies on a.h, that anyone including b.h really couldn't do without, then #include "a.h" should go in b.h
There is No difference in including a header file in .h or .c file.
The contents of the included file are just copy pasted in to the file in which you include it.
If you put the include directive in your header file, other files that include that header file will also get the included header.
foo.h:
#include "dependency.h"
bar.h:
#include "foo.h"
In this case, bar.h has both foo.h and dependency.h.
#include "a.h" expands to the contents of a.h.
If #include "a.h" is placed in b.h, then a.h will be copied into b.h during compilation.
If #include "a.h" is placed in b.c, then a.h will be copied into b.c during compilation instead.
.h files put at top of .c or .h files before compile
but .c files compile separately then link to getter to make executable file
You can include .c files - but by convention you do not.
.h files are for declarations - i.e. the .c file is the definition and the this .h file is going to do this. It is like the .h file is the contents of the cook book, and the .c file is the actual recipes.
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.
We do have a project wich uses the MIDL tool to create specific header/iid and proxy files. Those files are compiled and linked with the rest of the project using a post build step that calls nmake.
Is it possible to use precompiled headers with thos IDL generated files? How can I inject #include "stdafx-h" and remove other included headers?
Use the /FI option (Force Include): "This option has the same effect as specifying the file with double quotation marks in an #include directive on the first line of every source file specified on the command line, in the CL environment variable, or in a command file."
It won't remove the other headers, but this is not necessary for the Precompiled Header to be used... All the headers that you want to precompile should be included by stdafx.h. Then, provided the files have inclusion guards, it won't be a problem when they are included again in the sources.
Example
Generated a.cpp file:
#include <a.h>
#include <b.h>
//rest of the code
Suppose you want to pre-compile a.h and b.h. Then you create the file stdafx.h:
#include <a.h>
#include <b.h>
And then you use the /FI option to have this stdafx.h included as the first file into a.cpp. If the files a.h and b.h have include guards, leaving them in a.cpp is not an issue...
"stdafx.h" is merely a convention. If you know that yout generated source files always have a standard prefix of included headers, you can name the last of them in the /Yu switch (use precompiled headers). To create the PCH, create an single .cpp file with just those fixed headers and compile ith with /Yc.
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++: