The #inlcude C preprocessor directive

  • The C pre-processor can include (= read in) a file in place into a C program

  • The #include directive has 2 forms:

         #include  <filename>      - include file "filename" from 
                                     the C's standard include directory       
                                     (which is: /usr/include)
      
         #include "filename"       - include file "filename" from
                                     a user specified directory
      

  • The default user specified include directory is:

      • The current directory (.)

  • You can specify additional include directories using the C compiler option -Idir:

         gcc  -Idir1  -Idir2 ....  C-program

Common practice in C programming

  • Include files in C programs usually ends with the  .h (= "header file")

      • The include files are called header files because the #include directive almost always is located at the top (= head) of a C program file

    Example:

    include1.c header1.h
    #include "header1.h" //Header file
    
    int main( int argc, char* argv[] ) 
    {
       int a, b, c;
    
       c = square( a+b );
    }
    
    #define  square(x)  ((x)*(x)) 
    #define	 MAX	    99999
    
    
    
    
    
    
    

DEMO: /home/cs255001/demo/C/1-C-pre/include1.c + header1.h

Nested include files

  • The #include directive can nest"

      • An include file can contain #include directives that include other files !

    Example:

    include1.c Header files
    #include "header2.h" //Header file
    
    int main( int argc, char* argv[] ) 
    {
       int a, b, c;
    
       c = square( a+b );
    }
    
    header2.h:
    
      #include "header2-2.h"
    
      #define  MAX	  99999
    
    header2-2.h: #define square(x) ((x)*(x))

DEMO: /home/cs255001/demo/C/1-C-pre/include2.c + header2.h + header2-2.h

Nested include files can lead to recursion !!!

  • Warning

      • The nested include mechanism can lead to recursive inclusion

  • An uncontrolled recursive file include chain can can the C pre-processor to abort

  • Example of a recusive file inclusion chain:

    include-r.c recurse.h
    #include "recurse.h" //Header file
    
    int main( int argc, char* argv[] ) 
    {
       int x;
    
       x = MAX;
    }
    
     #include "recurse.h"  // Recursive    
                           // include chain    
    
     #define  MAX  99999
    
    
    
     

  • Note: we will learn how to break a recursive include chain in the next set of slides

DEMO: /home/cs255001/demo/C/1-C-pre/include-r.c + recurse.h