[root@kuldeep SharedLib]# ls header.h main.c myfunc.c myfunc.o
(2)//*** Create a Shared library form Object file "NOTE: .so file must Start with lib" [root@kuldeep SharedLib]# gcc -shared -o libmyfunc.so myfunc.o [root@kuldeep SharedLib]# ls header.h libmyfunc.so main.c myfunc.c myfunc.o
(3)//*** Linking with shared Library [root@kuldeep SharedLib]# gcc -Wall -o test main.c -lmyfunc /bin/ld: cannot find -lmyfunc collect2: error: ld returned 1 exit status
Solution:- [root@kuldeep SharedLib]# gcc -L/home/SharedLib -Wall -o test main.c -lmyfunc
[root@kuldeep SharedLib]# ls header.h libmyfunc.so main.c myfunc.c myfunc.o test
[root@kuldeep SharedLib]# ./test ./test: error while loading shared libraries: libmyfunc.so: cannot open shared object file: No such file or directory
(4)//*** Make library available at run time by setting LD_LIBRARY_PATH // Loader Can.t find shared file library Solution:- [root@kuldeep SharedLib]# LD_LIBRARY_PATH=/home/SharedLib [root@kuldeep SharedLib]# export LD_LIBRARY_PATH=/home/SharedLib
(6)//*** Making Library available at run time by rpath // -Wl portion sends comma-separated options to the linker, tell it to send the -rpath option to the linker with our working directory. gcc -L/home/SharedLib -Wl,-rpath=/home/SharedLib -Wall -o test main.c -lnewfunc -lmyfunc
(7)//*** If we want to Create two shared libraries //*** Follow same steps as :- //1. Create newfile.c //2. create newfile.h //3. Create PIC => gcc -c -Wall -Werror -fpic myfunc.c //4. Create Shared object => gcc -shared -o libmyfunc.so myfunc.o //5. Linking with Shared Library => gcc -L/home/SharedLib -Wl,-rpath=/home/SharedLib -Wall -o test main.c -lnewfunc -lmyfunc
[root@kuldeep SharedLib]# gcc -L/home/SharedLib -Wall -o test main.c -lmyfunc [root@kuldeep SharedLib]# ./test This is a Shared Library test.. I'm a shared library!
Creating shared Library Importance: whenever you are crating a large project have to build so many function on it. suppose if you want the same function to used in other project you have to copy that function and recompile it,share library give you feature that you can use a function of other project to your ongoing project which will save your time in testing and recompiling the tested function
steps for shared library Step1: Compile with position independent code gcc -c -Wall -Werror -fpic myfunc.c Step 2: Create a shared library from an object gcc -shared -o libmyfunc.so myfunc.o Step 3: Linked with shared Library gcc -L/home/adesh/mylib -Wall -o test main.c -lmyfunc Step 4: Making Library available at run time giving path at environmental variable export LD_LIBRARY_PATH =/home/adesh/mylib Step 5: Run ./test Output will be This is a Shared Library test.. I'm a shared library!
Here my files in directory mylib
[root@localhost mylib]# ls libmyfunc.so main.c myfunc.c myfunc.h myfunc.o test
you can see .so file which is a shared library which has been created in Step 2