next up previous
Next: Finding the dependencies Up: A simple Makefile Previous: A simple Makefile

Doing it all by hand

Suppose we want to write a module my_math that exports the functions fac() and fib() to compute the faculty and the fibonacci number. We write an interface for my_math in the file my_math.h, as shown in Figure 2.

  
Figure 2: my_math.h: interface of the module my_math.

It is a good habit to protect all the declarations in a .h file by #ifndef constructs. Now this file can be included as often as a user wants, without having the compiler complain about illegal redeclarations.

After we defined an interface for the module, we implement the functions in my_math.c (see Figure 3).

  
Figure 3: my_math.c: implementation of the module my_math.

Now we want to write a program that reads unsigned integers, and prints its faculty and fibonacci number, until we read something other than a number. We write a separate implementation for this in main.c. main.c includes my_math.h, the interface of the module my_math.

 
Figure 4: main.c: main routine.

To compile the program, we need an ANSI-C compiler, e.g. gcc. We can compile the program with the following command line:

 gcc -O2 -ansi -pedantic -Wall main.c my_math.c -o facfib

This produces a file facfib which can be executed directly. The default name of an executable is a.out, but it can be overridden by specifing -o file.

We can also compile the modules separately. The -c flag tells the compiler to generate an object file, and then stop.

 gcc -O2 -ansi -pedantic -Wall -c main.c
 gcc -O2 -ansi -pedantic -Wall -c my_math.c
 gcc main.o my_math.o -o facfib

The first command tells gcc to create main.o, the second command creates my_math.o and the last command links the two files to create the executable facfib.



Megens SA
Thu Jun 20 11:26:28 MET DST 1996