gcc - How to find what preprocessor does to a C program

There are gcc options that allow us to do only preprocessing or preprocessing and compiling or all preprocessing, compiling and linking to make an executable. If we need to see what does the compiler does during preprocessing we can ask it to do only preprocessing and see the result to find out what it does in preprocessing. This can be useful in many situations where we need to identify preprocessor errors, in academics etc.
Lets understand this with an example:
I am using Fedora8 with gcc - gcc (GCC) 4.1.2 20070925 (Red Hat 4.1.2-33)

Example contains a C file named "first.c" and a header file named "first.h" as following:

first.c
-------
#include "first.h"
#define MAX 10
int main()
{
int i;
int j;

printf("hello world \n");
i=MAX;
j=MIN;
printf("i - %d and MAX is %d\n",i,MAX);
printf("j - %d and MIN is %d\n",j,MIN);
return 0;
}
----

first.h
----
#ifndef __FIRST
#define __FIRST

#define MIN 5
#include <stdio.h>
#endif
----

if you compile the program and run it you will get
#gcc first.c
#./a.out
hello world
i - 10 and MAX is 10
j - 5 and MIN is 5

What we need to find out here is what preprocessor does to this program, as we all know, preprocessor does include the header file first.h in the program, which internally includes stdio.h (in my case it is /usr/include/stdio.h file), replaces MACROS (MIN and MAX here) with their values. In my case the gcc gives "-E" option for preprocessing only, find out your option by seeing manual page. So I run

#gcc -E first.c > first_only_preprocessor.out

and when you see the output file "first_only_preprocessor.out", you will find out what preprocessor does to our example C file.

Lets see, for example, what it does to our printfs, where we are printing MAX and MIN, I searched MAX and MIN in the output as follows:

# grep 'MIN\|MAX' first_only_preprocessor.out
OR
# gcc -E first.c | grep 'MIN\|MAX'

output is
printf("i - %d and MAX is %d\n",i,10);
printf("j - %d and MIN is %d\n",j,5);

As you see, preprocessor correctly replaces MAX with 10 and MIN with 5 :)

Think on the ideas where you can use this ...

No comments:

Books I like

  • Inside C++ Object Model
  • Unix Network Programming - Stevens
  • Professional-c++-programmer-to-programmer - wrox
  • Beautiful-code-leading-programmers-explain-how-they-think-theory-in-practice