Header File

Preprocessor

TheĀ C PreprocessorĀ is is just a text substitution tool to allow extra pre-processing before the actual compilation.

#ifndef MOTION2D_H
#define MOTION2D_H
 
...
#endif 
  • The above are Preprocessor directives - commands that allow transformations of the source code before it is compiled.

For C++

C++ has many tools such as inline functions that may be better suited compared to a preprocessor definition such as a macro.

Example

Seen in Lecture 7 of CS247. Consider an example: Linear Algebra modules.

// vec.h
struct Vec {
	int x,y;
};
// Matrix.h
#include "Vec.h"
struct Matrix {
	Vec e1;
	Vec e2;
};
// main.cc
#include "vec.h"
#include "Matrix.h"
 
int main() {
	Vec v1{1,2};
	vec v2{3,4};
	Matrix m{v1, v2};
}
 

main.cc includes vec.h main.cc includes matrix.h, includes vec.h

  • Without the #ifndef guard, there are two definitions of struct vec in main.cc, which is not allowed

To fix this issue of multiple definitions, use ā€œinclude guardsā€:

#ifndef 
#define
...
#endif
  • #ifndef VARIABLE: The code between #ifndef and #endif will only be seen by the compiler if VARIABLE is not defined.
  • #define VARIABLE defines a preprocessor variable.

Include Guard

#ifndef FILE_H
#define FILE_H
...
#endif

Works because once File.h is included once, the variable becomes defined, so in all future includes the block is omitted.

This doesn't fix all issues

There is an issue with circular dependencies. Consider the following example:

class A {
	B* myB;
}
class B {
	A* myA;
}

The issue is that each class needs to know the other exists before it can be created.

Solution: Break circular dependencies chain using Forward Declaration.

Preprocessor Directives

All preprocessor commands begin with a hash symbol (#).

DirectiveDescription
#defineSubstitutes a preprocessor macro.
#includeInserts a particular header from another file.
#undefUndefines a preprocessor macro.
ifdefReturns true if this macro is defined.
#ifndefReturns true if this macro is not defined.
#ifTests if a compile time condition is true.
#elseThe alternative for #if.
#elif#else and #if in one statement.
#endifEnds preprocessor conditional.
#errorPrints error message on stderr.
#pragmaIssues special commands to the compiler, using a standardized method.