C++ TUTORIALS - C++ Preprocessor
C++ Preprocessor
ADVERTISEMENTS
Predefined C++ Macros:
Macro | Description |
---|---|
__LINE__ | This contain the current line number of the program when it is being compiled. |
__FILE__ | This contain the current file name of the program when it is being compiled. |
__DATE__ | This contains a string of the form month/day/year that is the date of the translation of the source file into object code. |
__TIME__ | This contains a string of the form hour:minute:second that is the time at which the program was compiled. |
ADVERTISEMENTS
The #define Preprocessor:
#define macro-name replacement-textADVERTISEMENTS
#include <iostream> using namespace std; #define PI 3.14159 int main () { cout << "Value of PI :" << PI << endl; return 0; }
$gcc -E test.cpp > test.p ... int main () { cout << "Value of PI :" << 3.14159 << endl; return 0; }Function-Like Macros:
#include <iostream> using namespace std; #define MIN(a,b) (((a)<(b)) ? a : b) int main () { int i, j; i = 100; j = 30; cout <<"The minimum is " << MIN(i, j) << endl; return 0; }
The minimum is 30Conditional Compilation:
#ifndef NULL #define NULL 0 #endif
#ifdef DEBUG cerr <<"Variable x = " << x << endl; #endif
#if 0 code prevented from compiling #endif
#include <iostream> using namespace std; #define DEBUG #define MIN(a,b) (((a)<(b)) ? a : b) int main () { int i, j; i = 100; j = 30; #ifdef DEBUG cerr <<"Trace: Inside main function" << endl; #endif #if 0 /* This is commented part */ cout << MKSTR(HELLO C++) << endl; #endif cout <<"The minimum is " << MIN(i, j) << endl; #ifdef DEBUG cerr <<"Trace: Coming out of main function" << endl; #endif return 0; }
Trace: Inside main function The minimum is 30 Trace: Coming out of main functionThe # and ## Operators:
#include <iostream> using namespace std; #define MKSTR( x ) #x int main () { cout << MKSTR(HELLO C++) << endl; return 0; }
HELLO C++
cout << MKSTR(HELLO C++) << endl;
cout << "HELLO C++" << endl;
#define CONCAT( x, y ) x ## y
#include <iostream> using namespace std; #define concat(a, b) a ## b int main() { int xy = 100; cout << concat(x, y); return 0; }
100
cout << concat(x, y);
cout << xy;Predefined C++ Macros:
#include <iostream> using namespace std; int main () { cout << "Value of __LINE__ : " << __LINE__ << endl; cout << "Value of __FILE__ : " << __FILE__ << endl; cout << "Value of __DATE__ : " << __DATE__ << endl; cout << "Value of __TIME__ : " << __TIME__ << endl; return 0; }
Value of __LINE__ : 6 Value of __FILE__ : test.cpp Value of __DATE__ : Feb 28 2011 Value of __TIME__ : 18:52:48