Saturday, December 5, 2009

See the effect of C preprocessing with the -E option of gcc

Recently, I was interested in understanding better of one part of a C program, which is very generic, covering a lot of grounds with preprocessing options (#if ... #endif). However, I would like to see the minimum that covers the section I cared about. I vaguely remembered there is an option in the gcc compiler, from reading the book "An Introduction to GCC" a while ago, that can stop the process right after the preprocessing step (just like -c option stops after the compilation step). A quick check of "man gcc" revealed that it is -E:
-E Stop after the preprocessing stage; do not run the compiler proper. The output is in the form of preprocessed source code, which is sent to the standard output.

Input files which don't require preprocessing are ignored.

After setting the proper macros and running gcc with -E, I could immediately focus on the component to get what I wanted.

I have been using gcc for more than ten years, still there are more handy tricks to uncover.


Here is a simplified example showing the effect of the -E option. The following C function is saved in file "check_gcc_E.c".

--------------------------------------------------------------------------
#define GREETING "Hello World"

void check_gcc_E(void) {
#ifdef VERBOSE
printf("Macro VERBOSE is defined.\n");
printf("So you see: '%s'\n", GREETING);
#endif
printf("Hello everyone!\n");
}
--------------------------------------------------------------------------

gcc -E -DVERBOSE check_gcc_E.c

--------------------------------------------------------------------------
# 1 "check_gcc_E.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "check_gcc_E.c"

void check_gcc_E(void) {

printf("Macro VERBOSE defined\n");
printf("So you see: '%s'\n", "Hello World");

printf("Hello everyone!\n");
}
--------------------------------------------------------------------------

gcc -E check_gcc_E.c

--------------------------------------------------------------------------
# 1 "check_gcc_E.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "check_gcc_E.c"

void check_gcc_E(void) {
printf("Hello everyone!\n");
}
--------------------------------------------------------------------------

1 comment:

  1. I had similar experience getting started with gcc -- there are so many details untaught in a regular text. I think the Gough and Stallman book entitled "An Introduction to GCC" is really revealing, and practical. It is also quite short.

    Sorry I do not know "how to solve the overheating problem of the laptop". Google based on your specific settings.

    BTW, where is your fan exit located? Just from my own experience, I know of a notebook with fan exit on the back which caused trouble.

    ReplyDelete

You are welcome to make a comment. Just remember to be specific and follow common-sense etiquette.