Friday, August 29, 2014

header files


include in different forms

  • when declaring like this then compile looks for the header file in the following path in the unix
  • #include <file>
  •      /usr/local/include
         libdir/gcc/target/version/include
         /usr/target/include
         /usr/include
    
    
  • GCC looks for headers requested with #include "file" first 
    • in the directory containing the current file, 
    • then in the directories as specified by -iquote options, 
    • then in the same places it would have looked for a header requested with angle brackets.

Using unique macro ( include guards or guard macro)

  • It is also very common for headers to include other headers. 
  • For example This can lead to problems when header x.h and headery.h are included in a file, but both headers also include z.h. So header z.h is included twice.
  •  Most of time this will cause a compiler error, because of multiple declarations of a type or macro. There is a solution to this problem using the conditional compilation features of the preprocessor. The following illustrates the solution:

#ifndef UNIQUE_MACRO_NAME
#define UNIQUE_MACRO_NAME

/* body of header */

#endif

Can see one example:




File: header.h

#ifndef HEADER_EXAMPLE
#define HEADER_EXAMPLE

typedef long int INT32;      /* Used in prototype below so must be in header */
  
void f( INT32 );             /* external scope function prototypes go in header */

#endif

File: sub.c

#include <stdio.h>
#include "header.h"          /* " " in include causes compiler to look 
                                for header in the current working dir */

typedef double Real;         /* This type only used internally to this file, so 
                                it's not in header file */
static void g( INT32, Real );  /* internal scope function prototypes do not 
                                  go in header */

void f( INT32 x )
{
  g(x, 2.5);
}

static void g( INT32 x, Real d )
{
  printf("%f\n", x/d);
}

File: main.c

#include <stdio.h>
#include "header.h"

int main( void )
{
  INT32 x;

  printf("Enter a integer: ");
  scanf("%ld", &x);
  f(x);
  return 0;
}



Reference:

No comments:

Post a Comment