A sample function library that is implemented using global variables and functions in C:
// C program that implements a function library int var1; float var2; int f1( int x, float y ) { .... // body is not important in this discussion } int f2( int A[], int i, int j ) { .... // body is not important in this discussion } |
Question: how can other C functions use these (global) variables and functions ???
We must declare the global variables and functions in the function library before we use them:
// Declaration needed to // use global variables and functions in library extern int var1; extern float var2; int f1( int x, float y ); int f2( int A[], int i, int j ); // Functions that use the subsystem int main( ... ) { int a, b; var1 = 1234; ... f1( a, b ); ... } |
Unlike Java, we must provide the declaration information by ourselves in C !!!
C uses header files as the mechanism to provide the declarations information:
|
Every C program file has a header file that contains the declarations of the global variables and functions defined in the C program file:
progFile.c | progFile.h |
---|---|
int var1; float var2; int f1( int x, float y ) { .... // body } int f2( int A[], int i, int j ) { .... // body } |
// Declaration: extern int var1; extern float var2; int f1( int x, float y ); int f2( int A[], int i, int j ); |
You (the programmer) has to create the header file yourself.... (yes, it's tedious...)
We can now declare the global variables and the functions using an #include command:
// Declaration:
#include "progFile.h"
// Functions that use the subsystem
int main( ... )
{
int a, b;
var1 = 1234;
...
f1( a, b );
...
}
|
Note: the "...." quotes tells the C compiler to search the current directory for the included file
The C program that implements one stack of int:
#include <stdio.h> int stackTop = -1; int stackData[100]; void push(int x) { // check if stack is not full. if ( stackTop < 100 ) { stackData[++stackTop] = x; } } int pop( ) { // check if stack is not empty if ( stackTop > -1 ) { return( stackData[stackTop--] ); } return (-999999); // Pop empty stack error } |
The header file stack.h is:
extern int stackTop; extern int stackData[100]; void push(int x); int pop( ); |
A C program that want to use this stack implemention only need to #include "stack.h to declare the (global) variables and functions in the stack.c program:
#include <stdio.h>
#include "stack.h"
int main(int argc, char *argv[])
{
push(1); push(4); push(7); push(9);
printf("%d\n", pop());
printf("%d\n", pop());
printf("%d\n", pop());
printf("%d\n", pop());
printf("%d\n", pop());
}
|
|