Using Object Files and Libraries - Unix

Here is a program in the file selection.c that does selection sort. As you can see, it uses three functions.

  1. One function reads a sequence of integers.
  2. One function prints a sequence of integers.
  3. And one function rearranges a sequence of integers using selection sort.

Here is how we might compile and run this program:

    % gcc -Wall -W -o selection selection.c
    % selection

It is easy to imagine that the three functions could be handy in writing other programs. We can decompose the original program into three files:

  1. intArray.h that contains declarations for the three functions
  2. intArray.c that contains the definitions of the three functions
  3. selectionMain.c that contains the main function of the program.

If you look in selectionMain.c, you will see that it includes the file intArray.h, thus knows the prototypes of the three functions and the compiler can make sure that they are used correctly in selectionMain.c.

The three files can be used as follows:

    % gcc -Wall -W -o selection selectionMain.c intArray.c
    % selection

The first of these two commands compiles selectionMain.c and intArray.c and links them together to create the executable file selection. The second of these commands executes the selection file.

We could have achieved exactly the same result with the commands:

    % gcc -Wall -W -c intArray.c
    % gcc -Wall -W -c selectionMain.c
    % gcc -o selection selectionMain.o intArray.o
    % selection

The first command creates the intArray.o file, the second command creates the selectionMain.o file. Notice that now if we have a bug in intArray.c we need only recompile the intArray.c file [and then link]. And if we have a bug in selectionMain.c we need only recompile the selectionMain.c file [and then link]. By the way, in Unix people use the utility make to manage compilations, linking, libraries, and the like.

Since the odds are that the three functions will be debugged once and then used in many programs, we may even save the object file intArray.o in a library [later we may keep also other useful object files in this library].

Here is how we can create the library file, say, cis71.a :

   % ar  -qs  cis71.a  intArray.o 

and here is how we can use this library to create the executable file selection:

   % gcc  -Wall -W -o selection selectionMain.c  cis71.a