Preprocessor commands |
We have already explained the use of #include files to import header files into programs. When the compiler evaluates:
#include "file.h";
it inserts all of the code in file.h into the file being compiled. In general, this inserts prototypes of functions that are needed in your file.
There are other preprocessor commands that are used to control the compilation of your program. One that you have seen in a lot of my programs follows the pattern below:
#ifndef NODE_H_ #define NODE_H_ ... // code #endif /*NODE_H_*/
The compiler directive tells it to include the material between the #ifndef and #endif only if the macro NODE_H_ is not yet defined. The statement #define NODE_H_ defines that macro (as empty - the actual definition does not matter, only that it has been defined).
Thus when this file is included the first time, everything in it is included into the file. However, if it is included a second time, then the contents will be skipped. Because including a file more than once will likely really confuse the compiler, you should always wrap the contents of ".h" files with these preprocessor commands, where the name of the macro is related to the name of the file as above.
Another way of using preprocessors is controlling the insertion of debug commands. For example, in the following
#ifdef DEBUG cout << "This is the test version, i=" << i << endl; #else cout << "This is the production version!" << endl; #endif
the second line will be executed if the preprocessor command #define DEBUG occurs earlier in the program, and the 4th line will be executed if not. More likely, it will be used as follows
#ifdef DEBUG cout << debugging values << endl; #endif
Note that #undef DEBUG can be used to undefine a macro.
Preprocessor commands |