Monday, March 26, 2012

#include directive in C

Include files are used to define data structures, constants, and function prototypes for items used by multiple modules. it is possible to put code in an include file, but this is rarely done.

Style for #Includes

,Most programs put the #include directives in a group just after the heading comments. That way they are all together in a known place. System includes are enclosed in <>) come first, followed by any local includes (enclosed in "" ).
Example:
/********************************************************
 *   ... heading comments ....                          *
 ********************************************************/
/* System includes */
#include <stdio.h>
#include <alloc.h>
#include <string.h>
/* Local includes */
#include "key.h"
#include "table.h"
#include "blank.h"
#include directives come just after the heading comments. Put system includes first, followed by local includes.
#include directives that use absolute file names, that is specify path and name, such as /user/sam/program/data.h and Y:\DEVELOP\PROGRAM\DEFS.H make your program non-portable. If the program is moved to another machine, even one using the same operating system, the source will have to be changed.
The solution is to never use absolute paths. The compiler can be pointed to the correct directory by using the -I option. That way you need to change only one Makefile instead of a bunch of source files.
/* Non portable */
#include "/user/sam/program/data.h"
/* Portable, compile with "-I/user/sam/program" */
#include "data.h"
Do not use absolute paths in #include directives. Let the -I compile opt

Protecting against double #Includes

Include files can contain #include directives. This means that you can easily include the same file twice. For example, suppose database.h and symbol.h both need the file defs.h . Then, putting these lines:
#include "database.h"
#include "symbol.h"
in your program brings in two copies of defs.h . Defining a structure or type twice can cause errors. So how do you avoid this problem? The solution is t conditional compilation to prevent the double include from causing trouble.
#ifndef _DEFS_H_INCLUDED_
#define _DEFS_H_INCLUDED_
And at the end, insert this line:
#endif /* _DEFS_H_INCLUDED_ */
The first time through, _DEFS_H_INCLUDED_ is not defined.
The #ifndef causes the entire body of the file to be included and _DEFS_H_INCLUDED_ to be defined. Therefore, when the file is include the #ifndef kicks in, and the entire body of the file is now #ifdef 'ed out.

No comments:

Post a Comment