× Home
Next Lec → ← Previous Lec

C Pre-processor introduction & working

Quick Recap

  • Compiler converts textual form of a C program into an executable.
  • There are four phases for a C program to become an executable:
    • Preprocessing → Compilation → Assembly → Linking

What happens in Preprocessing

  • Removal of comments
  • Expansion of macros
  • Expansion of include files

What happens in compilation

  • Generation of assembly level instructions

What happens in assembly

  • '.o' and '.exe' is created
  • but function calls are not resolved here (printf)
  • Assembly level instruction are converted in to machine code.

What happens in linking

  • Lins the function implementations

What is a C preprocessor

  • C preprocessor comes under action before the actual compilation process.
  • C preprocessor is not a part of the c compiler
  • It is a text substitution tool
  • All preprocessor commands begin with a hash symbol(#)

Preprocessor commands example

  • #define
  • #include → inserts other header files
  • #undef
  • #ifdef
  • #ifndef
  • #if
  • #else
  • #elif

#include <stdio.h>
// This is requesting all the content which resides in stdio header file

The # INCLUDE DIRECTIVE

Two common #include formats

  • In C programming there are two common formats for #includes:
    • #include < headerfile.h > // The angles brackets say to look in the standard system directories
    • #include "myfile.h" // The quotation marks say to look in the current directory.
  • Disk drive full path is allowed, but discouraged since it is not portable:
    • #include <C:\Program files\Harry\bhau\somefile.h > // Too specific
    • #include <sys/file.h> // Relative and porable path to the standard locations.

The #define directive

Using #define for debugging

  • #define directive can be used for debugging
  • We can have printing statements that we only only active when debugging
  • We can "protect" them in a "ifdef" block as follows:
    • #define DEBUG
      #ifdef DEBUG // if DEBUG is defined then execute below statements
      // executable code
      #undef DEBUG

Macros using #define

  • We can also create macros using #define
  • Macors operate much like functions, but because they are expanded in place and are generally faster
                        
                        #define PI 3.14
                        #define SQUARE (x) x*x // made like a function
                        int radius = 5;
                        int area = PI * SQUARE(radius); // area = 3.14 * radius * radius and this will resolve during preprocessing time