Datasheet

Your library is now ready to use. You can add to the list of files to be used by the compiler to create your
program like this:
$ gcc -o program program.o libfoo.a
$ ./program
bill: we passed Hello World
$
You could also use the –l option to access the library, but because it is not in any of the standard places,
you have to tell the compiler where to find it by using the
–L option like this:
$ gcc –o program program.o –L. –lfoo
The –L. option tells the compiler to look in the current directory (.) for libraries. The –lfoo option tells
the compiler to use a library called
libfoo.a (or a shared library, libfoo.so, if one is present). To see
which functions are included in an object file, library, or executable program, you can use the
nm com-
mand. If you take a look at
program and lib.a, you see that the library contains both fred and bill,
but that
program contains only bill. When the program is created, it includes only functions from the
library that it actually needs. Including the header file, which contains declarations for all of the func-
tions in the library, doesn’t cause the entire library to be included in the final program.
If you’re familiar with Windows software development, there are a number of direct analogies here,
illustrated in the following table.
Shared Libraries
One disadvantage of static libraries is that when you run many applications at the same time and they
all use functions from the same library, you may end up with many copies of the same functions in
memory and indeed many copies in the program files themselves. This can consume a large amount of
valuable memory and disk space.
Many UNIX systems and Linux-support shared libraries can overcome this disadvantage. A complete
discussion of shared libraries and their implementation on different systems is beyond the scope of this
book, so we’ll restrict ourselves to the visible implementation under Linux.
Shared libraries are stored in the same places as static libraries, but shared libraries have a different filename
suffix. On a typical Linux system, the shared version of the standard math library is
/lib/libm.so.
When a program uses a shared library, it is linked in such a way that it doesn’t contain function code
itself, but references to shared code that will be made available at run time. When the resulting program
is loaded into memory to be executed, the function references are resolved and calls are made to the
shared library, which will be loaded into memory if needed.
Item UNIX Windows
object module
func.o FUNC.OBJ
static library
lib.a LIB.LIB
program
program PROGRAM.EXE
13
Chapter 1: Getting Started
47627c01.qxd:WroxPro 9/28/07 8:56 PM Page 13