How does preprocessed code look?
You can use the -E
option with the GCC compiler to stop after preprocessing and display the preprocessed code. Here's a simple example:
Example: Preprocessor Directives with GCC
// main.c
#include <stdio.h>
// Define a constant
#define PI 3.14159
// Define a macro function
#define SQUARE(x) ((x) * (x))
int main() {
int radius = 5;
float area = PI * SQUARE(radius);
printf("Area of the circle: %f\n", area);
return 0;
}
To view the preprocessed code, you can use the following command in your terminal:
gcc -E main.c -o main_preprocessed.c
This will preprocess the code and save the result in a file named main_preprocessed.c
. You can then open this file to see the preprocessed code:
cat main_preprocessed.c
The preprocessed code will look something like this:
// contents of stdio.h will be pasted here
// I'm just showing the line that declares the printf function
// in the stdio.h header file
extern int printf (const char *__restrict __format, ...);
// rest of stdio.h
int main() {
int radius = 5;
float area = 3.14159 * ((radius) * (radius));
printf("Area of the circle: %f\n", area);
return 0;
}
This is just a snippet of the preprocessed code. You can see how the preprocessor has replaced the macro PI
with its value and expanded the SQUARE
macro in the code. The preprocessed code includes all the header files and macro substitutions, giving you a clearer view of what the compiler sees before actual compilation.