C++ Pre-processor Directives are used to control how something is compiled, and are identified with a ‘#’ prefix. They do not need a semicolon (;) at the end of the line. A backslash (\) can be used to extend a directive to multiple lines, because pre-processor directives end with ‘\n’, and a ‘\’ will escape the ‘\n’ character.
#include
The file being #include‘d is substituted in the location where the directive is placed. To include a file in the same directory, use double quotes. E.g.
#include "cprogram.h"
To include a file from the system (the includes path), use the <> signs. E.g.
#include
Convention says to include C++ files without the ‘.h’ extension, and C files with the ‘.h’ extension.
To make sure that a file is not included multiple times, place ‘#pragma once’ at the top of the file being included. This will work similar to the ‘include_once()’ PHP function, except that here the code must be in the file being included instead of the file doing the including.
A “variable `Classname Varname’ has initializer but incomplete type” error is probably because you forgot to #include a class definition file.
#define
Macros define a given symbol to be something else. Wherever the symbol appears within the program, it will be replaced with the contents of the macro. Special characters including ‘#’, ‘@’ are not allowed. A ‘\’ is used to escape characters. Example:
#define somesym(x) newsym(x)
This defines all instances of somesym() as newsym(), and also requires that somesym() have an argument.
Macros can make programs much larger, because they are substituted exactly before compiling. A macro that has 8 characters but is defined as 50 characters, used 20 times inside a program, will take up 1000 characters, instead of 160. Thus there is a speed/disk size tradeoff when using macros.
#pragma
‘#pragma once’ at the top of a file prevents it from being included multiple times by a ‘#include’.
#if/elif/else/endif
These directives are used for conditional compilation. ‘elif’ means else-if. ‘elif’ and ‘else’ are optional, while ‘endif’ is required. This will make it so that certain statements are not compiled unless a certain condition is met. They are limited in that they can only evaluate constant expressions, including macro expressions.
#ifndef/ifdef
#ifndef means if not defined, and ifdef means if defined. Similar to #if, but these can only check whether a symbol has been defined using #define. Variables cannot be accessed during pre-processing, only #define’s. In the following example, the #if/endif and #ifndef/ifdef clauses do the same thing:
#define somesym(x) newsym(x) #if defined(somesym) //statements #endif #ifndef somesym //statements #endif