Creating and Using Shared Libraries (.so) on Linux
Creating and Using Shared Libraries (.so) on Linux
Overview
A shared library, known as a dynamic linking library in Linux, is a file that can be loaded into memory at runtime rather than being linked during compilation. This approach reduces executable size and enables centralized updates of libraries.
These libraries typically use the .so extension on Linux systems. Unlike static libraries, shared libraries allow multiple programs to utilize the same memory space for the library code, thus optimizing resource usage. Common system libraries like libc, libpthread, and libssl are implemented as shared libraries.
Building a Shared Library
To create a shared library from source files using GCC, follow these steps:
# Example directory structure
# --sodir
# |-- libsource.c
# |-- libsource.h
# |-- libmylib.so
gcc -fPIC -shared -o libmylib.so libsource.c
Key flags used:
-fPIC: Generates position-independent code required for shared libraries.-shared: Instructs the linker to produce a shared object instead of an executable.-o: Specifies the output filename.
The naming convention for shared libraries requires a lib prefix followed by the library name and the .so suffix. Deviating from this convention may prevent the system from recognizing the library.
Using a Shared Library
First, define a function in a source file named libhello.c:
#include <stdio.h>
void hello() {
printf("Hello, world!\n");
}
Compile it into a shared library:
gcc -fPIC -shared -o libhello.so libhello.c
Next, write enother program that uses this library in main.c:
void hello();
int main() {
hello();
return 0;
}
Link the shared library when compiling the main program:
gcc -o main main.c -L. -lhello
In this command:
-L.: Inndicates the current directory where the shared libray resides.-lhello: Refers tolibhello.so, omitting thelibprefix and.sosuffix.
When executing the program, you might encounter an error indicating the library cannot be found. To resolve this issue, update the LD_LIBRARY_PATH environment variable:
export LD_LIBRARY_PATH=$(pwd)
Alternative methods include:
- Temporarily setting the environment variable.
- Adding the path to
/etc/profile. - Including the path in
~/.bashrc. - Modifying
/etc/environment.