-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpreprocessors.c
96 lines (77 loc) · 2.08 KB
/
preprocessors.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/**
* @file preprocessors.c
* @author PantheraRed
* @brief A C program to demonstrate the use of preprocessors.
* @version 0.1
* @date 2022-07-17
*
* @copyright Copyright (c) 2022
*
*/
// Includes a header file
#include <stdio.h>
// Defines a macro
#define MAX_LENGTH 5
// If the macro is defined, the code is executed
#ifdef MAX_LENGTH
#undef MAX_LENGTH
#define MAX_LENGTH 10
#endif
// If the macro is undefined, the code is executed
#ifndef MAX_LENGTH
#define MAX_LENGTH 20
#endif
// If condition is true, the code is executed
#if 1 > 2
#define RESULT "1 > 2"
#elif 1 < 2
#define RESULT "1 < 2"
// Else the other code is executed
#else
#define RESULT "1 == 2"
#endif
// If DEBUG is defined, it defines the macro DEBUG_PRINT as a function
#ifdef DEBUG
#define DEBUG_PRINT(x) printf(x)
// Else the macro is defined as a null function
#else
#define DEBUG_PRINT(x)
#endif
// If macro is undefined, error is printed
// #ifndef SOME_MACRO
// #error "SOME_MACRO is not defined"
// #endif
void print_startup_message();
void print_exit_message();
// Pragma directive is compiler specific
// For example, GCC does not support startup or exit so the following code will not work in GCC:
// #pragma startup print_startup_message
// #pragma exit print_exit_message
// Alternative to the code above for GCC
void __attribute__((constructor)) print_startup_message();
void __attribute__((destructor)) print_exit_message();
void print_startup_message()
{
printf("This is startup message\n");
}
void print_exit_message()
{
printf("This is exit message\n");
}
// To print message during the time of compilation
// #pragma message "This is a compiler message"
// To poison an identifier in GCC
// #pragma GCC poison printf
int main()
{
int i, a[MAX_LENGTH] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
printf("a: ");
for (i = 0; i < MAX_LENGTH; i++)
{
printf("%d ", a[i]);
}
printf("\nMAX_LENGTH: %d\n", MAX_LENGTH); // 10
printf("RESULT: %s\n", RESULT); // 1 < 2
DEBUG_PRINT("Only prints when -DDEBUG flag is passed to the GCC\n");
return 0;
}