Why shared libraries ??
- They reduce memory consumption if used by more than one process, and they reduce the size of the executable.
- They make developing applications easier: a small change in the implementation of a function in the library don't need the user to recompile and relink his application code every time. You need to only relink if you make incompatible changes, such as adding arguments to a call or changing the size of a struct.
1. Creating Object File with Position Independent Code
All the code that goes into a shared library needs to be position independent. We can make gcc emit position-independent code by passing it one of the command-line switches -fpic or -fPIC (the former is preferred, unless the modules have grown so large that the relocatable code table is simply too small in which case the compiler will emit an error message, and you have to use -fPIC).
First we will create object files for all .c files that goes into a shared library.
gcc -c -fPIC calc.c -o calc.oAbove we are compiling calc.c with -fPIC option and generating calc.o object file.
2. Creating Shared library with the Object File
Every shared library has a prefix "lib", the name of the library, the phrase ".so", followed by a period and a version number that is incremented whenever the interface changes (as a special exception, the lowest-level C libraries don't start with "lib").
gcc -shared -o libcalc.so calc.oAbove command on successful produces a shared library named "libcalc.so".
- -shared: Produces a shared object which can then be linked with other objects to form an executable.
3. Using the Shared Library
Now let us link the created shared library with our application. Compile main.c as shown below
$ gcc -o test main.c -lcalc /usr/bin/ld: cannot find -lcalc collect2: ld returned 1 exit statusThe linker doesn’t know where to find libcalc_mean. But why ?
GCC has a list of places to look by default for shared libraries, but our directory is not in that list. Bingo that's the reason compilation failed at linking level.
Now we need to tell GCC where to find libcalc_mean.so. We will do that with the -L option.
gcc -o test main.c -lcalc_mean -L/home/cf/slib
- -l option tells the compiler to look for a file named libsomething.so The something is specified by the argument immediately following the “-l”. i.e. -lmean
- -L option tells the compiler where to find the library. The path to the directory containing the shared libraries is followed by "-L".
No comments:
Post a Comment