Saturday, January 18, 2014

Headers and Includes: Why and How

Organize your directories so that each class has its own header file (.hpp) with the class declaration and its own implementation file (.cpp) with the source code for the class methods.

Your main() function will be in its own .cpp file and all the .cpp files will be compiled into .obj files, which will then be linked into a single program by the linker.

http://www.cplusplus.com/forum/articles/10627/

The #include statement is basically like a copy/paste operation. The compiler will "replace" the #include line with the actual contents of the file you're including when it compiles the file.

The difference between Header files and Source files? Basically, header files are #included and not compiled, whereas source files are compiled and not #included. Files with header extensions might be ignored by the compiler if you try to compile them.

1) Only #include things you need to include (covered next section)
2) Guard against incidental multiple includes with include guards.

An Include Guard is a technique which uses a unique identifier that you #define at the top of the file. Here's an example:

1
2
3
4
5
6
7
8
//x.h

#ifndef __X_H_INCLUDED__   // if x.h hasn't been included yet...
#define __X_H_INCLUDED__   //   #define this so the compiler knows it has been included

class X { };

#endif 


This works by skipping over the entire header if it was already included. __X_H_INCLUDED__ is #defined the first time x.h is included -- and if x.h is included a second time, the compiler will skip over the header because the #ifndef check will fail.

Always guard your headers. Always always always. It doesn't hurt anything to do it, and it will save you some headaches.

No comments:

Post a Comment