Creating a shared library:
The shared library is one of the types of libraries which we use in Linux. Generally, the files with extension '.so' represents Shared library object. Here, I am going to explain about how to create a shared library and how to invoke it in our programs.
The file a.c is our library's C source file.
a.c:
The file a.c is our library's C source file.
a.c:
#include "head.h"
void printfn(void)
{
int a = 3, b = 2;
int c = 9;
printf("\nThe power of %d to %d is %d\n", a, b, c);
}
The Head.h file is the header file where we have the declaration of the functions which are defined in the library.
The Head.h file is the header file where we have the declaration of the functions which are defined in the library.
Head.h:
void printfn(void);
The d.c file is the C source of the executable which we are going to generate which is going to use our shared library.
d.c:
#include
#include "head.h"
int main ()
{
printfn();
return 0;
}
The new.sh file has the definitions to include LD_LIBRARY_PATH variable which is essential for linking the shared library with the executable. The users who does not have admin permissions, will not be able to set LD_LIBRARY_PATH environment variable which is needed to locate the shared library.
New.sh:
#!/bin/sh
export LD_LIBRARY_PATH=/temp:$LD_LIBRARY_PATH
exec /temp/output_file $
The Makefile has the definition for generating our shared library.
Makefile:
LIBNAME = mylib
SOLIBVER = 1.0
RM = rm
AR = ar
RANLIB = ranlib
CC = gcc
LN = ln
SHAREDLIB = lib$(LIBNAME).so
LSRCS = a.c
LOBJS = $(LSRCS:.c=.o)
SHOBJS = $(LSRCS:.c=.od)
%.od: %.c
$(CC) -fPIC -c -o $@ $<
all:: shared
shared: $(SHAREDLIB).$(SOLIBVER)
$(SHAREDLIB).$(SOLIBVER): $(SHOBJS)
$(CC) -o $@ -shared -Wl,-soname,$@ $^
$(LN) -s $@ $(SHAREDLIB)
clean::
$(RM) $(SHOBJS) $(SHAREDLIB).$(SOLIBVER) $(SHAREDLIB)
Steps:
The following is the list of steps which we need to do to execute our program after linking our generated shared library.
The following is the list of steps which we need to do to execute our program after linking our generated shared library.
1)
1) Make
1) Make
2) 2) gcc –o output_file d.c
3) 3) chmod 777 new.sh
4) 4) ./new.sh