Development Environment: Ubuntu7.04, gcc4.1.2 create a shared library so1 and math1.c on Ubuntu7.04, and enter nanomath1.cintadd (intx, inty) {returnx + y in the command line ;} 2. compile and generate the shared library libmath1.sogcc-fPIC-shared-olibmath1.somath1.c3 and create the test program testmath. c
Development Environment: Ubuntu 7.04, gcc 4.1.2
Create shared library so with C on Ubuntu 7.04
1. Create math1.c and enter nano math1. c in the command line.
Int add (int x, int y)
{
Return x + y;
}
2. compile and generate the shared library libmath1.so
Gcc-fPIC-shared-olibmath1.so math1.c
3. Create the test program testmath. c and enter nano testmath. c In the command line.
# Include
Int main ()
{
Int x = 10, y = 18;
Int sum = add (x, y );
Printf ("% d + % d = % d \ n", x, y, sum );
Return 0;
}
4. compile and generate the test program testmath.
Gcc-otestmath-lmath1 testmath. c-L = ./
5. Run the test program and enter./testmath in the command line.
The following error occurs:
./Testmath: error while loading shared libraries: libmath1.so: cannot open shared object file: No such file or directory
6. Copy libmath1.so to the default shared library loading path (/lib or/usr/lib) in Linux)
Enter sudo cp libmath1.so/usr/lib/in the command line/
7. Run the test program testmath again.
Result: 10 + 18 = 28
Gcc compilation parameters:
-FPIC generates location-independent code so that the Library can be connected and loaded at any location.
-Shared represents the shared library.
-O links to generate a library or program with a specified name
-L specify the shared library to be linked
-L specify the path of the Shared Library