[previous_group] [previous] [up] [next] [next_group]

Conditional Compilation

With the latest set of improvements, we now have a program, stock6.c, (with its associated utilities) that meets the spec and is somewhat tolerant of user errors. We can run this program interactively or in a batch mode, using redirection.

But we saw that in batch mode, the prompts we give the user get in the way. We used comments to remove the printf()'s for the prompts. The problem with this is that we need to remember all the locations in the code where we have these printf()'s to turn them on or off.

The C preprocessor provides a feature that allows us to do this called conditional compilation.

When we want to build our program to work with files instead of the keyboard we want to compile it without the prompt printf()'s sometimes, and when we want to build our program to work interactively with the user at the keyboard at other times.

The preprocessor provides compiler directives which allow us to sometimes compile the code one way and compile it a different way at other times. These are:

     #ifdef <ident>
     #endif

where <ident> is a macro name.

For example, we can write:

        #ifdef INTERACT
        printf("\nEnter number of shares(EOF to quit): ");
        #endif

Similarly, we can use this technique for turning debugging on and off. The modified code is in stock7.c.

Notice:

We can now compile this program as:
        cc stock7.c stock_utils.o


[up] to Overview.

[next]