Section 28.1 Intro to Libraries
Now that we have created our own data types and functions that allow us to manipulate instances of objects of these new types it is common to package such functions as a library. Take as an example our arbitrarily large integers. In order to allow others to use these numbers in their code it would make sense to “hide” and package up all the work and messiness that goes into creating such a number. You’d probably even want to provide some additional functionality such as adding, subtracting, multiplying, dividing two such number and then hand all that to a user who just wants to be able to work with really large numbers (but has no interest in how you implemented that functionality). That’s where libraries come in.
We have actually already encountered libraries in our work, for example the standard input/output library stdio
, the standard library stdlib
and the math library math
. Each such library actually comes with two files, one ending in .h
(the so-called header file) and one ending in .o
(the so-called object file.
The header file contains all of the prototypes of functions from the library (remember, the compiler needs to know about these prototypes so that it can check whether you are using your functions correctly). That’s why we need to #include ...
the header files of those libraries whose functions we wish to invoke in our code.
The object file contains the actual library functions in machine language. It’s already been translated by the compiler so that when you build your program you don’t have to compile the entire library each time around. You can simply link the translated code contained in the library object file to your own code (that’s what the linker does.)
So here is an example. Suppose you are writing a C-program coolProgram.c
that uses functions from the two libraries stdio
and math
. In order for the compiler to have access to all of the function prototypes from these libraries, we need to:
#include <stdio.h>
#include <math.h>
Once your program compiles without any compiler errors, the compiler produces an object file coolProgram.o
, which is your code, translated into machine language. Next, the linker starts its job and finds the object files that contain the input/output functions and math functions used in your program, namely stdio.o
and math.o
. These object files contain all of these functions already compiled into machine language. The linker then links (packages) these object files together with the object file coolProgram.o
of the program you are writing, and if all goes well, an executable file results.
Activity 28.1.
Which of the following are part of a library?
a header file
an object file
source code
Please paste your text submission into the box below, then select Run
to submit it: