How Dynamic Libraries Work


In our first programs, all of the code was contained within the source file. Such programs are called statically-linked executables, because they contained all of the necessary functionality for the program that wasn't handled by the kernel. In the programs we wrote in Chapter 6, we used both our main program file and files containing routines used by multiple programs. In these cases, we combined all of the code together using the linker at link-time, so it was still statically-linked. However, in the helloworld-lib program, we started using dynamic libraries. When you use dynamic libraries, your program is then dynamically-linked, which means that not all of the code needed to run the program is actually contained within the program file itself, but in external libraries.

When we put the -lc on the command to link the helloworld program, it told the linker to use the c library (libc.so) to look up any symbols that weren't already defined in helloworld.o. However, it doesn't actually add any code to our program, it just notes in the program where to look. When the helloworld program begins, the file /lib/ld-linux.so.2 is loaded first. This is the dynamic linker. This looks at our helloworld program and sees that it needs the c library to run. So, it searches for a file called libc.so in the standard places (listed in /etc/ld.so.conf and in the contents of the LD_LIBRARY_PATH environment variable), then looks in it for all the needed symbols (printf and exit in this case), and then loads the library into the program's virtual memory. Finally, it replaces all instances of printf in the program with the actual location of printf in the library.

Run the following command:

 ldd ./helloworld-nolib 

It should report back not a dynamic executable. This is just like we said - helloworld-nolib is a statically-linked executable. However, try this:

 ldd ./helloworld-lib 

It will report back something like

       libc.so.6 => /lib/libc.so.6 (0x4001d000)       /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x400000000) 

The numbers in parenthesis may be different on your system. This means that the program helloworld is linked to libc.so.6 (the .6 is the version number), which is found at /lib/libc.so.6, and /lib/ld-linux.so.2 is found at /lib/ld-linux.so.2. These libraries have to be loaded before the program can be run. If you are interested, run the ldd program on various programs that are on your Linux distribution, and see what libraries they rely on.




Programming from the Ground Up
Programming from the Ground Up
ISBN: 0975283847
EAN: 2147483647
Year: 2006
Pages: 137

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net