CS 70

Preprocessor

What You’re Given…

  • You have a .cpp file (source file) from the programmer.
  • You also have several header files that you know about.

What You’ll Do…

You'll make a new piece of C++ code which is an exact copy of the source file, except that you must deal with preprocessor directives. A preprocessor directive is a line that begins with a # (pronounced “hash”).

The first time you act as the preprocessor, create a file in your group's directory (e.g., preprocessed-01.txt). If you come back to this stage, you need to make a new file (e.g., preprocessed-02.txt).

#include directives

Replace any line that looks like #include followed by a filename as follows:

  • If the filename is in quotes, look for it in the user's files
  • If the filename is in angle brackets, look for it in the system's files

If you can't find the file, you need to write an error message and stop.

If you do find the file, replace the #include line with the contents of that header file. Put a comment around the block of text you've pasted like this.

// Begin content from file: foo.hpp

(actual contents of foo.hpp)

// End content from file: foo.hpp

And then start over in that pasted content, looking to see if you have # lines in that pasted content to deal with.

#define directives

The #define directive defines a macro. A macro is a fragment of code that has been given a name. Whenever the name is used, it is replaced by the contents of the macro. This is useful for defining constants or for code that is used multiple times.

For example, the following code:

#define PI 3.14

Defines a macro named PI that is replaced by 3.14 wherever it appears in the code.

float area = PI * radius * radius;

In this example, you need to go through and do a search and replace to find the name PI and replace it with 3.14. You only replace it if it's a whole word and not in a string. So PIES_ARE_NICE would not be become 3.14ES_ARE_NICE.

#if and #ifdef directives

These directives let you delete code so the compiler won't see it. Specifically, the code only survives if the #if or #ifdef is true.

  • #if checks if a condition is true (e.g., 3 < 4)
  • #ifdef checks if a macro is defined — the code only survives if the macro is defined
  • #ifndef checks if a macro is not defined — the code only survives if the macro is not defined

When doing this part:

  • If the code survives, just remove the #if or #ifdef and #endif lines.
  • If the code doesn't survive, remove everything and leave a comment saying that the code was removed because the condition was false.

When You've Finished

  • If you successfully created the preprocessed file, you can move on to the next stage, compilation.
  • If however there was an error, you need to fix just that error in the source file and create a new copy of that source file in your group directory, number that too, so it becomes prog-01.cpp.

(When logged in, completion status appears here.)