[Univ of Cambridge] [Dept of Engineering]
next up previous contents
Next: Multiple Source Files Up: Source File organisation Previous: Source File organisation

Preprocesser Facilities

The preprocessor has some useful options.
sourcefile inclusion :-

#include "defines.h"
...
#include <defines.h>
The difference between these two variants is that with the included file in quotes, it is first looked for in the directory of the source file. In each case, the standard include directories on the system are searched as well as any directories mentioned on the command line after the `-I' flag. See the `cpp' man page for more details.

macro replacement :-

Note that these macros are expanded before the compiler is called. They aid legibility. In the first example below, a simple substitution is done. In the second, an in-line macro is defined, whose execution should be faster than the equivalent function.

#define ARRAY_SIZE 1000
char str[ARRAY_SIZE];
...
#define MAX(x,y) ((x) > (y) ? (x) : (y))
int max_num;
    max_num = MAX(i,j);
...

conditional inclusion :-

Blocks of code can be conditionally compiled according to the existence or value of a preprocessor variable. A variable can be created using the `#define' preprocessor directive or using the `-D' option at compilation time. The first two examples shows how debugging statements can easily be switched on or off. The final example shows how blocks of code can be de-activated.

#ifdef DEBUG
  printf("got here\n");
#else
  something();
#endif /*DEBUG*/
...

#if defined(DEBUG)
#define Debug(x) printf(x)
#else
#define Debug(x)
#endif

 if ( i == 7 ){
     j++;
     Debug(("j is now %d\n", j));
 }

#if 0
 /* this code won't reach the compiler */
 printf("got here\n");
#endif


next up previous contents
Next: Multiple Source Files Up: Source File organisation Previous: Source File organisation
Tim Love
1999-10-06