The C preprocessor
See what the compiler do on a code
Define macros
Prohibit the use of a function
Writing macros replacing functions
Predefined macros
Conditional macros
See what the compiler do on a code
Define macros
Prohibit the use of a function
Writing macros replacing functions
Predefined macros
Conditional macros
The C preprocessor
In the whole article, the compiler used is GCC.See what the compiler do on a code
It is possible to see what the compiler do with the following command.gcc -E -P code.c
Define macros
A basic exemple:#define THING here is the thingProhibit the use of a function
It is possible to prohibit the use of a function with macros, for example we can write the following macro:#define sprintf USE_SNPRINTF_NOT_SPRINTFWriting macros replacing functions
It is possible to write macros that have a similar functionality that a function, here is an example:#include <stdio.h>
#define MIN(X, Y) ((X) < (Y) ? (X) : (Y))
int main(int argc,char* argv[]) {
printf("The minimum beetween 3 and 4 is %d\n",MIN(3,4));
printf("The minimum beetween a and b is %c\n",MIN('b','a'));
printf("The minimum beetween a+3 and b is %c\n",MIN('b','a'+3));
return 0;
}
/*
hanoo@hp_laptop % ./a.out
The minimum beetween 3 and 4 is 3
The minimum beetween a and b is a
The minimum beetween a+3 and b is b
*/#include <stdio.h>
#define MIN(X, Y) ((X) < (Y) ? (X) : (Y))
#define PRINT_MIN(A, B) printf("The minimum beetween %s and %s is %d\n",#A,#B,MIN(A,B));
#define BEGIN int main(int argc,char* argv[]) {
#define END return 0;}
BEGIN
PRINT_MIN(3,4);
PRINT_MIN('b','a');
PRINT_MIN('b','a'+3);
END
/*
./a.out
The minimum beetween 3 et 4 is 3
The minimum beetween 'b' and 'a' is 97
The minimum beetween 'b' and 'a'+3 is 98
*/#include <stdio.h> #define MIN(X, Y) ((X) < (Y) ? (X) : (Y)) #define PRINT_MIN(A, B) printf("The minimum beetween %s and %s is %d\n",#A,#B,MIN(A,B)); #define BEGIN int main(int argc,char* argv[]) { #define END return 0;} #define MACRO_PROGRAMME BEGIN \ PRINT_MIN(3,4); \ PRINT_MIN('b','a'); \ PRINT_MIN('b','a'+3); \ END MACRO_PROGRAMME /* ./a.out The minimum beetween 3 et 4 is 3 The minimum beetween 'b' and 'a' is 97 The minimum beetween 'b' and 'a'+3 is 98 */
Predefined macros
It is possible to see all the predefined macros by entering the following command:gcc -dM -E - < /dev/null
| __FILE__ | the name of the current file |
| __LINE__ | the line number |
| __DATE__ | the date of compilation |
| __TIME__ | the time of compilation |
Conditional macros
It is possible to cancel a definition with the command '#undef name'.| #ifdef name | Includes code until '#endif' iff name is defined |
| #if expr | If expr is true (operation on integer constants) until include '#endif' |
| #ifndef nom | Includes code until '#endif' iff name is not defined |
| #else | The else that we know |
| #elif | The else if that we know |