[Intro to UNIX Software Development]

THE C PREPROCESSOR


Tool to transform code before compilation


Inclusion of header files


Macro definition and expansion


Conditional compilation

  • #ifdef NAME and #ifndef NAME will only insert contained code if NAME is or isn't defined (respectively). End with #endif
  • Example:
    	#define FOO
    	#ifdef FOO
    	  ... this gets included ...
    	#endif
    	#ifndef FOO
    	  ... this does NOT get included ...
    	#endif
    	
  • #if allows more complicated expressions with a C-like syntax (combine terms with &&, ||, and ! and also use integer operations)
  • The defined() function returns 1 iff a variable is defined. These two lines are identical:
    	#ifdef FOO
    	#if defined(FOO)
    	
  • #elif NAME, #else, #endif
  • To omit code, use:
    	#if 0
    	... code to be omitted
    	#endif
    	
    Rather than commenting it out. This eliminates problems with nested comments.


    Demo

  • Uses the files foo, bar, and blah.
    		/lib/cpp -P foo
    		/lib/cpp -P -DINCLUDE_BAR foo
    		/lib/cpp -P -DINCLUDE_BLAH foo
    


    [BACK][FORWARD]


    Prepared by Erik Nygren (nygren@mit.edu) and Mike Whitson (mwhitson@mit.edu)