Jun 7, 2016

C Programming #62: Typical Header file

C Programming #62: Typical Header file

This article will explore on the content of stdio.h , stdlib.h, stdint.h. It will try to correlate things already discussed. On broad way it will cover

  1. General content of header file.
  2. Internal identifiers.
  3. Why are header file required ?
  4. Method to protect multiple inclusion of header file.

stdio.h file can located here - /usr/include/stdio.h. Open it in your favourite editor and try to correlate with sections to follow.

General content of header file

  • Preprocessors - Go through the article Pre-processor
    • #define e.g

      # define _STDIO_H       1
      ...
      # define __need_size_t
      ...
      #define _IOFBF 0
      ...
      # define __ssize_t_defined
      
    • #ifdef and #ifdefined

      #ifndef __USE_FILE_OFFSET64
      typedef _G_fpos_t fpos_t;
      #else
      typedef _G_fpos64_t fpos_t;
      #endif
      ...
      #ifndef EOF
      # define EOF (-1)
      #endif
      
    • #include

  • Structure forward declaration - Go through article Structure forward declaration

    struct obstack;
    ...
    struct _IO_FILE;
    
  • Structure protoype - Go through article Structure introduction. See in header file /usr/include/stdlib.h

    typedef struct
    {
       int quot;
       int rem;
    } div_t;
    
  • Typedef - Go through article Typedef. See in header file /usr/include/stdint.h

    typedef signed char             int8_t;
    typedef short int               int16_t;
    typedef int                     int32_t;
    
  • Function prototype - Go through article Functions. See in header file /usr/include/stdio.h

    extern int printf (const char *__restrict __format, ...);
    

Internal identifiers

Note in header file there are lot of identifiers with _ or __ prefixing the name. e.g

# define _STDIO_H       1
#ifdef __USE_XOPEN2K8

Note these identifier are to be used only internally, and should not be used in User Progam. Also when user is using his own identifier like variable name/ function name… user should not prefix it with _ or __ unless he is extending on of these standard header file like stdio.h

Why are header file required ?

To understand the real nead of header file we need to see how to write a library module, which will be covered in later part of articles. But do remember that header file export to #defines, typedef, function we he could in his program.

Method to protect multiple inclusion of header file.

What would happen if stdio.h is included twice? Will it get really get included twice ? Answer is no. It is done on purpose, so that every header files gets included only once so that there is no redefinition of things. To achive this you can observe that following boiler plate code is used

#ifndef _STDIO_H
# define _STDIO_H       1
....
#endif /* !_STDIO_H */
Above condition inclusion will prevent the content of stdio.h to be included twice.

No comments :

Post a Comment