Download Practical C Programming - International Research Institute MICA

Transcript
308
Chapter 18: Modular Programming
If we had written:
File main.c
static int
flag = 0;
/* flag is off */
main()
{
printf("Flag is %d\n", flag);
}
File sub.c
static int
flag = 1;
/* flag is on */
then flag in main.c is an entirely different variable from flag in sub.c.
However, you should still give the variables different names to avoid confusion.
Headers
Information that is shared between modules should be put in a header file. By
convention, all header filenames end with .h. In our infinite array example, we use
the file ia.h.
The header should contain all the public information, such as:
•
A comment section describing clearly what the module does and what is available to the user
•
Common constants
•
Common structures
•
Prototypes of all the public functions
•
extern declarations for public variables
In our infinite array example, over half of the file ia.h is devoted to comments.
This level of comment is not excessive; the real guts of the coding are hidden in
the program file ia.c. The ia.h file serves both as a program file and as documentation to the outside world.
Notice there is no mention in the ia.h comments about how the infinite array is
implemented. At this level, we don’t care about how something is done; we just
want to know what functions are available. Look through the file ia.h (see Example
18-1).
Example 18-1: File ia.h
/********************************************************
* Definitions for the infinite array (ia) package.
*
*
*
* An infinite array is an array whose size can grow
*