Shared libraries are reusable libraries which can be used by multiple applications at the same time. The advantages of shared libraries are<\/p>\n
Only disadvantage compared to statically linked library is, there is an overhead for loading the library and resolving the symbols at run time.<\/p>\n
In case of loading during application start, the loader will load the library into process virtual address space and resolve before the application is launched.<\/p>\n
In case of loading dynamically the same can be achieved with the respective system library apis when in need..<\/p>\n
Windows it will be a dynamically linked library(*.dll) and uses the same PE format as windows executable.<\/p>\n
Linux it will be a shared object(*.so) and uses the ELF format as a normal linux executable.<\/p>\n
In linux use the -shared gcc option to create a shared object. if your library name provided is abc.so, the linux linker will create it as libabc.so.<\/p>\n
While statically linking, the option -labc should be provided to link with the same.<\/p>\n
If you are using dynamic linking, you need to use dlopen(3) ,dlsym(3) and dlclose(3) apis to load, access the symbol and unload the library.<\/p>\n
Sample codes<\/p>\n
application.c<\/p>\n
#include <stdio.h>
\n#include “call_lib.h”<\/p>\nint main(int argc, char * argv[])
\n{
\nprintf(“In application\\n”);
\ncall_lib(3);<\/p>\nreturn 0;
\n}<\/p>\ncall_lib.h<\/p>\n
int call_lib(int num);<\/p>\n
library.c<\/p>\n
#include <stdio.h>
\n#include “call_lib.h”<\/p>\nint call_lib(int num)
\n{
\nprintf(“passed value is %d\\n”, num);<\/p>\nreturn 0;
\n}<\/p>\nTo compile the library code
\ngcc -shared -fPIC -o library.so library.c<\/p>\nTo compile the application code
\ngcc -o sample -L \/home\/yogi\/libs -lrary application.c<\/p>\nRunning the executable<\/p>\n
set first the library path<\/p>\n
$export LD_LIBRARY_PATH=\/home\/yogi\/libs:$LD_LIBRARY_PATH
\n$ .\/sample
\nIn application
\npassed value is 3<\/p><\/blockquote>\n