When a large number of functions are used, we will have a very long list of function declarations
Schematically:
Program file that make use of library functions | Library program with useful functions (e.g.: push, pop, etc (stack)) |
---|---|
#include <stdio.h>
int f(float x); // Declare f !!!
float g(int x); // Declare g !!!
float h(float x); // Declare h !!!
....
int main( int argc, char *argv[])
{
short a = 2;
int b;
b = f( a ); // Works correctly now
printf("a = %d, b = %d\n", a, b);
}
|
// File: /home/cs255001/demo/C/Multi-file-prog/r2.c #include <stdio.h> int f( float x ) { return(x*x); } float g( int x ) { return(x*x*x); } float h( float x ) { return(x*x*x*x); } ... (possibly more functions)... |
|
// File: /home/cs255001/demo/C/Multi-file-prog/r2.c #include <stdio.h> int f( float x ) { return(x*x); } float g( int x ) { return(x*x*x); } float h( float x ) { return(x*x*x*x); } |
// File: /home/cs255001/demo/C/Multi-file-prog/r2.h // This #ifndef trick is used to prevent recursive include..... #ifndef h_prog2_h #define h_prog2_h int f( float x ); float g( int x ); float h( float x ); #endif |
(You can create this file easily using cut and paste from the function definitions in file r2.c !!!)
Example:
|
How to run the program:
cd /home/cs255000/demo/C/Multi-file-prog gcc -c r1.c gcc -c r2.c gcc r1.o r2.o a.out Output: cs255-1@aruba (4995)> a.out a = 2, b = 4 a = 2, b = 8 a = 2, b = 16 No errors !!! |
|
Example: (taken from this lecture webpage click here) this C program contains both a declration and a definition of the function int f(short x):
#include <stdio.h> int f(short x); // function declaration !!! int main(int argc, char *argv[]) { short x = 2; // *** short !!! int y = 0; y = f(x); // Assumes: int f(int x) printf("x = %d, y = %d\n", x, y); } /* --------------------------------------------------- Function f( ) is defined AFTER main's use of f( ) --------------------------------------------------- */ int f(short x) // Function definition !!! { return(x*x); } |
|
Example:
// File: /home/cs255001/demo/C/Multi-file-prog/r2.c
#include <stdio.h>
#include "r2.h" // Include header files for functions in r2.c !!
int f( float x )
{
return(x*x);
}
float g( int x )
{
return(x*x*x);
}
float h( float x )
{
return(x*x*x*x);
}
|
The program c2.c will compile correctly !!!
|
|