Thursday, January 28, 2010

Trivia of Preprocessor

The preprocessor's role in the compilation process is:
C program -> (Preprocessor) -> modified C program -> (Compiler) -> Object code.
The preporcessor executes the directives and remove them in the process (make those lines empty), and replace the #define directives wherever they appeared later in the file.

Three types of preprocessing directives:
  1. Macro definition: #define, #undef
  2. File inclusion: #include
  3. Condition compilation: #if, #ifdef, #ifndef, #elif, #else, #endif. (others include #error, #line, #progma)
#undef N : removes the current definition of macro N. If N has not been defined, #undef has no effect. Usually this is used to give a new definition to existing macro.

Several predefined Macros:
  • __LINE__ : line number of file being compiled
  • __FILE__ : name of file being compiled
  • __DATA__ : mm dd yyyy
  • __TIME__ : hh:mm:ss
#if defined DEBUG // same as #if defined (DEBUG)
...
#endif
Since 'defined' tests only where DEBUG is defined or not, it is not necessary to give DEBUG a value. Just use: #define DEBUG

#ifdef DEBUG // equivalent to #if defined DEBUG
#endif

#ifndef DEBUG // equivalent to #if !defined DEBUG
-------------------
#ifdef WIN32
...
#elif defined MAC
...
#elif defined LINUX
...
#else
#error no operation system chosen
#end

Use following to condition out the block of codes:
#if 0
...
#endif
Reminder: those block of codes are not completely ignored. Comments are processed before preprocessing. If you have unterminated comments between #if 0, #endif, you still get compile error (like you have /*abcdefg ). Unpaired quote could give you a warning.

#error message : usually the compiler will terminate immediately without trying to find other errors
#if MAX < 10000
# // it is legal to use null directive
#error max value is too small
#
#endif

No comments:

Post a Comment