Preprocessor is taking effect before the real compiling.
A preprocessor is a text substitution step happended before actual compilation.
All preprocessor commands begin with a pound symbol #
.
The following table lists the often used preprocessor directives.
Directive | Description |
---|---|
#define | define a preprocessor macro |
#include | Inserts a particular header from another file |
#undef | Undefines a preprocessor macro |
#ifdef | Returns true if this macro is defined |
#ifndef | Returns true if this macro is not defined |
#if | Tests if a condition is true |
#else | The alternative for #if |
#elif | #else #if in one statement |
#endif | Ends preprocessor conditional |
#error | Prints error message on stderr |
#pragma | Issues special commands to the compiler |
The following line defines MAX_LENGTH as 20.
#define MAX_LENGTH 20
After this definition we can have code like
int i = 20*MAX_LENGTH;
When the compiler sees the MAX_LENGTH
it will replace it with 20, which is defined in the #define
.
The following directives load foundation.h from Foundation Framework and add the text to the current source file and then load myheader.h from the local directory and add the content to the current source file.
#import <Foundation/Foundation.h>
#include "myheader.h"
The following two lines first undefine a value and then define that value.
#undef FILE_SIZE #define FILE_SIZE 42
The following line defines MESSAGE only if MESSAGE isn't already defined.
#ifndef MESSAGE #define MESSAGE "You wish!" #endif
The following table lists existing macros.
Macro | Description |
---|---|
__DATE__ | The current date as a character literal in "MMM DD YYYY" format |
__TIME__ | The current time as a character literal in "HH:MM:SS" format |
__FILE__ | This contains the current filename as a string literal. |
__LINE__ | This contains the current line number as a decimal constant. |
__STDC__ | Defined as 1 when the compiler complies with the ANSI standard. |
#import <Foundation/Foundation.h> int main() { NSLog(@"File :%s\n", __FILE__ ); NSLog(@"Date :%s\n", __DATE__ ); NSLog(@"Time :%s\n", __TIME__ ); NSLog(@"Line :%d\n", __LINE__ ); NSLog(@"ANSI :%d\n", __STDC__ ); return 0; }
The following code uses preprocessor to create a function like macro.
#import <Foundation/Foundation.h> #define message_for(a, b) \ NSLog(@#a " and " #b ": We love you!\n") int main(void) { message_for(Carole, Debra); return 0; }
The following code uses preprocessor to find out the bigger value.
#import <Foundation/Foundation.h>
#define MAX(x,y) ((x) > (y) ? (x) : (y))
int main(void)
{
NSLog(@"Max between 20 and 10 is %d\n", MAX(10, 20));
return 0;
}