C By Example Part 2: C Preprocessor
In short: Using the option -E the gcc tool chain stops after running the C preprocessor (CPP). The result of CPP gets written to stdout (i.e. it gets written to the terminal). Use this to see what input the compiler actually gets.
Supplement: More About Preprocessor Directives
If you want to learn more about the preprocessor the internet is your friend. There are many web sites with great content, here are two of them:
-
C Preprocessor (on gcc.gnu.org) is very comprehensive and perfect to look up each and every detail.
-
C Preprocessor (on Wikipedia) gives a nice overview and summarizes all the other directives not mentioned in the video.
Supplement: Compiler Options for Macro Definition
Consider
1 | hello world!
|
With the option -D (man gcc) one can define macros. For example
theon$ gcc -Dhello=Hallo -Dworld=Welt -E foo.c # 0 "foo.c" # 0 "<built-in>" # 0 "<command-line>" # 1 "foo.c" Hallo Welt! theon$
CPP uses this options as if the first two lines of input file would be
1 2 | #define hello Hallo
#define world Welt
|
You also can use the -D option to define an empty macro. Consider this source file with a conditional directive:
1 2 3 4 5 | #ifdef de
Hallo Welt!
#else
hello world!
#endif
|
with -Dde the macro is defined for the preprocessor processes the first line of the source file:
theon$ gcc -E bar.c # 0 "bar.c" # 0 "<built-in>" # 0 "<command-line>" # 1 "bar.c" hello world! theon$ gcc -Dde -E bar.c # 0 "bar.c" # 0 "<built-in>" # 0 "<command-line>" # 1 "bar.c" Hallo Welt! theon$
Food for Thoughts
How could you use the -D option so that the token dummy gets expanded to the two tokens foo bar?
Quiz 04
Consider the following C program:
1 2 3 4 5 6 7 8 | What
the(bloody hell);
is
this()
{
thing(doing);
}
|
Add some directives but otherwise do not change the content so that it can be compiled with
1 | gcc obscure.c
|
into an executable that prints
1 | hello, world!
|
Submit your solution with submit hpc quiz04 obscure.c
Note: There are no automatic tests and hence you will get no confirmation email. However, if there is no error message then the submission was successful. And if there was an error message then not successful. ;-)