Preprocessor

Compiler instructions to be carried out before the actual compilation.

 

Always begins with a hash symbol #

 

Not terminated with a semi-colon ;

 

Used when compiling the program.

 

The most common preprocessor directives are: #include and #define

 

#define Defines a preprocessor macro
#include Substitues a preprocessor macro
#undef Undefines a macro
#ifdef Returns TRUE if macro is defined
#ifndef Returns TRUE if macro is not defined
#if Tests if a compile time condition is TRUE
#else the alternative for #if
#elif #else and #if in one statement
#endif Ends preprocessor conditional
#error Prints error message on stderr

 

 

Conditional Compilation can be carried out by utilising the various conditional preprocessor directives stated above. This example defines (or in this case, sets) a condition to be checked upon:

#include <iostream>
using namespace std;

#define DEBUG

int main () {

	#ifdef DEBUG
		cerr << "Debug message goes here." << endl ;
	#endif

	cout << "This simply shows what happens when the above DEBUG" << \
			" (not a keyword) is defined/set." << endl ;

	#ifdef DEBUG
		cerr << "Debug message goes here." << endl ;
	#endif

	cout << "Comment out the above #define preprocessor directive to 'turn off' " << \
			"debugging comments." << endl ;

	#ifdef DEBUG
		cerr << "Debug message goes here." << endl ;
	#endif

	return 0;
}
Debug message goes here.
Debug message goes here.
Debug message goes here.
This simply shows what happens when the above DEBUG (not a keyword) is defined/set.
Comment out the above #define preprocessor directive to 'turn off' debugging comments.

 

 

The # preprocessor operator can be used to convert specified text into a quoted string:

#include <iostream>
using namespace std;

#define STRINGTHIS( a ) #a  //note, using same argument after #

int main () {

	cout << STRINGTHIS(Hello World!) << endl ;

	return 0;
}
Hello World!

Leave a Reply