L-40 MCS 275 Wed 18 Apr 2001
Below is the listing of the main program (stored in fibmain.c ) :
/* L-40 MCS 275 Wed 18 Apr 2001 : illustration of the make utility. */
/* Suppose we wish to create a program to compute the Fibonacci
numbers once iteratively and once recursively.
The program below is the main program that calls "Fib".
There are two different implementations of "Fib", the
recursive one is in the file fibrec.c, the iterative one
is in the file fibitr.c. With "make" we create two different
executable main programs : fbwrec and fbwitr. */
#include <stdio.h>
extern int Fib ( int n );
/* returns the n-th Fibonacci number */
int main ()
{
int n;
printf("\nCalculation of Fibonacci numbers\n");
printf("Give a natural number : "); scanf("%d",&n);
printf("Fibonacci number #%d is %d.\n",n,Fib(n));
return 0;
}
The recursive implementation for Fib is in the
file fibrec.c :
/* recursive implementation of the calculation of Fibonacci numbers */
int Fib ( int n )
{
if (n == 0 || n == 1)
return 1;
else
return Fib(n-1) + Fib(n-2);
}
The iterative implementation for Fib is in the file
fibitr.c
/* iterative implementation of the calculation of Fibonacci numbers */
int Fib ( int n )
{
int previous,current,temp,i;
previous = 1;
current = 1;
for (i = 1; i < n; i++)
{
temp = previous + current;
previous = current;
current = temp;
}
return current;
}
The makefile that helps creating all executables is here :
# Illustration of make file to create different executables from
# one main program with different versions of subroutines.
# All intendations at beginning of line are TABs.
# To create the executable programs, type "make fbwrec", and
# "make fbwitr", for the respective recursive and iterative versions.
# Type "make all" to create everything.
# With "make clean" we clean up all object files and executables.
# compiler directives :
compile = gcc -c
link = gcc -o
# recursive and iterative versions of Fibonacci function :
fibrec.o: fibrec.c
@echo compiling fibrec
@$(compile) fibrec.c
fibitr.o: fibitr.c
@echo compiling fibitr
@$(compile) fibitr.c
# main program :
fibmain.o: fibmain.c
@echo compiling fibmain
@$(compile) fibmain.c
# the executables :
fbwrec: fibrec.o fibmain.o
@echo linking...
@$(link) fbwrec fibrec.o fibmain.o
@echo done, executable is in fbwrec
fbwitr: fibitr.o fibmain.o
@echo linking...
@$(link) fbwitr fibitr.o fibmain.o
@echo done, executable is in fbwitr
fib: fibrec.c fibmain.c
gcc -p fibrec.c fibmain.c
# make the versions with the profiler :
pfbwrec: fibrec.c fibmain.c
cc -p -o pfbwrec fibrec.c fibmain.c
pfbwitr: fibitr.c fibmain.c
cc -p -o pfbwitr fibitr.c fibmain.c
# making everything :
all: fbwrec fbwitr pfbwrec pfbwitr
# clean up the directory
clean:
@echo cleaning object files and executables
@/bin/rm -f -r *o fbwrec fbwitr pfbwrec pfbwitr