SlideShare a Scribd company logo
1 of 32
LIBRARIESLIBRARIES
Ashwanth SAshwanth S
LIBRARIES
It is a file containing compiled code that is to be
incorporated later into a program.
It is of two types:
1. Static library
2. Shared library
Static Library
● An archive (or static library) is simply a collection of
object files stored as a single file.
● Static libraries end with the ``.a'' suffix. This collection
is created using the ar (archiver) program.
● When the linker encounters an archive on the
command line, it searches the archive for all
definitions of symbols (functions or variables) that are
referenced from the object files that it has already
processed but not yet defined.
● The object files that define those symbols are extracted
from the archive and included in the final executable.
Creating a static library
● Compile: gcc -Wall -g -c prog1.c prog2.c
-Wall: include warnings
-g : include debugging info
● Create library:ar rcs libname.a prog1.o prog2.o
● List files in library: ar -t libctest.a
● Linking with the library:
➢ gcc -o executable-name prog.c libname.a
➢ gcc -o executable-name prog.c -L/path/to/library-
directory -lname
Shared Library
● A shared library (also known as a shared object, or as
a dynamically linked library) is similar to a archive in
that it is a grouping of object files.
● The most fundamental difference is that when a shared
library is linked into a program, the final executable
does not actually contain the code that is present in the
shared library. Instead, the executable merely contains
a reference to the shared library.
Creating a shared library
● Create library:
gcc -Wall -fPIC -c prog1.c prog2.c
gcc -shared -o libname.so prog1.o prog2.o
● You can create a seperate directory for your
shared libraries. Eg /opt/lib where opt is a
directory that is reserved for all the software
and add-on packages that are not part of the
default installation.
● You can move the created shared library to that directory.
Eg: mv libname.so /opt/lib
● If you are creating the library with version number eg
libname.so.x where x is the version number you have to
link the file as shown below.
ln -sf /opt/lib/libname.so.x /opt/lib/libname.so
● The link to /opt/lib/libname.so allows the naming
convention for the compile flag -lctest to work.
● Compile main program and link with shared object
library:
gcc -Wall -o prog prog.c -L/opt/lib -lname
● The shared library dependencies of the executable
can be listed with the command: ldd name-of-
executable
eg: ldd prog
● The output of ldd may show something like
below:
libname.so => not found
● You can fix this by following one of the
method below:
a) export LD_LIBRARY_PATH=/opt/lib
b) During compiling you could add rpath as below
gcc -o prog prog.c -L/opt/lib -lname 
-Wl,-rpath=/opt/lib
c) You can add the path of the library in
etc/ld.so.conf.d/libc.conf
● To update the cache use
sudo ldconfig
● Now if you check the dependencies the not found
would have disappeared.
● In LD_LIBRARY_METHOD the environmental
variable vanishes once you close the terminal so
you have to specify the path again and again
● In rpath the path is added to the executable so you
dont have to mention it again for that one.
● If you have added the library path in libc.conf the
libraries will be searched there automatically.
● Note:
➢ Suppose that both libname.a and libname.so are
available.Then the linker must choose one of the
libraries and not the other.
➢ The linker searches each directory (first those
specified with -L options, and then those in the
standard directories).
➢ When the linker finds a directory that contains either
libtest.a or libtest.so, the linker stops searching the
directories.
➢ If only one of the two variants is present in the directory,
the linkerchooses that variant.
➢ Otherwise, the linker chooses the shared library version,
unless you explicitly instruct it otherwise.You can use the
-static option to demand static archives.
➢ For example, the following line will use the libname.a
archive, even if the libname.so shared library is also
available:
gcc -static -o prog prog.c -L/opt/lib –lname
● These shared libraries are dynamically linked.
● Even though the dynamic linker does a lot of the work for
shared libraries, the traditional linker still has a role to play
in creating the executable.
● The traditional linker needs to leave a pointer in the
executable so that the dynamic linker knows what library
will satisfy the dependencies at runtime.
● The dynamic section of the executable requires a
NEEDED entry for each shared library that the executable
depends on.
● The dynamic linker is the program that manages
shared dynamic libraries on behalf of an
executable.
● The essential part of the dynamic linker is fixing up
addresses at runtime, which is the only time you
can know for certain where you are loaded in
memory. A relocation can simply be thought of as
a note that a particular address will need to be fixed
at load time.
● Shared libraries can also be loaded at times other than
during the startup of a program. They're particularly
useful for implementing plugins. Eg adobe plugin in
browser..
● To use dynamic loading functions,include the
<dlfcn.h> header file and link with the –ldl option to
pick up the libdl library.
Functions in dynamic loaading
● The dlopen function opens a library
void * dlopen(const char *filename, int flag);
eg:
dlopen("/opt/lib/libname.so", RTLD_LAZY);
RTLD_LAZY: If specfied there is no concern
about unresolved symbols until they are
referenced.
RTLD_NOW: All unresolved symbols are resolved
when dlopen() is called.
● dlerror()
Errors can be reported by calling dlerror(), which
returns a string describing the error from the last
call to dlopen(), dlsym(), or dlclose(). One point to
note is that after calling dlerror(), future calls to
dlerror() will return NULL until another error has
been encountered.
● dlsym()
The return value from the dlopen function is a void
* that is used as a handle for the shared library.You
can pass this value to the dlsym function to obtain
the address of a function that has been loaded with
the shared library.
● dlclose()
The dlclose function unloads the shared library.
● The executable is created for dynamic loading
as below
gcc -rdynamic -o progdl progdl.c -ldl
● Thus library is dynamically loaded.
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>
#include "ctest.h"
int main(int argc, char **argv)
{
void *lib_handle;
double (*fn)(int *);
int x;
char *error;
lib_handle = dlopen("/opt/lib/libctest.so",
RTLD_LAZY);
if (lib_handle==NULL)
{
fprintf(stderr, "%sn", dlerror());
exit(1);
}
fn = dlsym(lib_handle, "ctest1");
if ((error = dlerror()) != NULL)
{
fprintf(stderr, "%sn", error);
exit(1);
}
(*fn)(&x);
printf("Valx=%dn",x);
dlclose(lib_handle);
return 0;
}
Benefits of Static Libraries
● Static libraries cannot eliminate duplicated
code in the system. However, there are
other benefits to using static libraries. Some
of these benefits are as follows:
● Static libraries are simple to use.
● The static library code does not need to be
position-independent code.
Benefits of Shared Libraries
● Code sharing saves system resources.
● Several programs that depend on a common
shared library can be fixed all at once by
replacing the common shared library.
● The environment can be modified to use a
shared library.
● Programs can be written to load dynamic
libraries without any prior arrangement at link
time.

More Related Content

What's hot

Program Structure in GNU/Linux (ELF Format)
Program Structure in GNU/Linux (ELF Format)Program Structure in GNU/Linux (ELF Format)
Program Structure in GNU/Linux (ELF Format)
Varun Mahajan
 

What's hot (20)

Self-Hosted Scripting in Guile
Self-Hosted Scripting in GuileSelf-Hosted Scripting in Guile
Self-Hosted Scripting in Guile
 
Introduction to the LLVM Compiler System
Introduction to the LLVM  Compiler SystemIntroduction to the LLVM  Compiler System
Introduction to the LLVM Compiler System
 
Program Structure in GNU/Linux (ELF Format)
Program Structure in GNU/Linux (ELF Format)Program Structure in GNU/Linux (ELF Format)
Program Structure in GNU/Linux (ELF Format)
 
Logback
LogbackLogback
Logback
 
Assembler
AssemblerAssembler
Assembler
 
嵌入式Linux課程-GNU Toolchain
嵌入式Linux課程-GNU Toolchain嵌入式Linux課程-GNU Toolchain
嵌入式Linux課程-GNU Toolchain
 
LLVM Compiler - Link Time Optimization
LLVM Compiler - Link Time OptimizationLLVM Compiler - Link Time Optimization
LLVM Compiler - Link Time Optimization
 
.NET Core Blimey! (Shropshire Devs Mar 2016)
.NET Core Blimey! (Shropshire Devs Mar 2016).NET Core Blimey! (Shropshire Devs Mar 2016)
.NET Core Blimey! (Shropshire Devs Mar 2016)
 
Mbuild help
Mbuild helpMbuild help
Mbuild help
 
Beginning with Composer - Dependency manager in php
Beginning with Composer  - Dependency manager in php Beginning with Composer  - Dependency manager in php
Beginning with Composer - Dependency manager in php
 
Robot operating system [ROS]
Robot operating system [ROS]Robot operating system [ROS]
Robot operating system [ROS]
 
Understanding Implicits in Scala
Understanding Implicits in ScalaUnderstanding Implicits in Scala
Understanding Implicits in Scala
 
Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scala
 
Indic threads pune12-apache-crunch
Indic threads pune12-apache-crunchIndic threads pune12-apache-crunch
Indic threads pune12-apache-crunch
 
CNIT 126 Ch 7: Analyzing Malicious Windows Programs
CNIT 126 Ch 7: Analyzing Malicious Windows ProgramsCNIT 126 Ch 7: Analyzing Malicious Windows Programs
CNIT 126 Ch 7: Analyzing Malicious Windows Programs
 
Java.util.concurrent.concurrent hashmap
Java.util.concurrent.concurrent hashmapJava.util.concurrent.concurrent hashmap
Java.util.concurrent.concurrent hashmap
 
Python Streaming Pipelines with Beam on Flink
Python Streaming Pipelines with Beam on FlinkPython Streaming Pipelines with Beam on Flink
Python Streaming Pipelines with Beam on Flink
 
web programming Unit VI PPT by Bhavsingh Maloth
web programming Unit VI PPT  by Bhavsingh Malothweb programming Unit VI PPT  by Bhavsingh Maloth
web programming Unit VI PPT by Bhavsingh Maloth
 
Python Streaming Pipelines on Flink - Beam Meetup at Lyft 2019
Python Streaming Pipelines on Flink - Beam Meetup at Lyft 2019Python Streaming Pipelines on Flink - Beam Meetup at Lyft 2019
Python Streaming Pipelines on Flink - Beam Meetup at Lyft 2019
 
Apache Crunch
Apache CrunchApache Crunch
Apache Crunch
 

Viewers also liked

Viewers also liked (7)

Dough Slapper or Dough Master: Building Reports for Papa John's
Dough Slapper or Dough Master:   Building Reports for Papa John'sDough Slapper or Dough Master:   Building Reports for Papa John's
Dough Slapper or Dough Master: Building Reports for Papa John's
 
Práctica 1b
Práctica 1bPráctica 1b
Práctica 1b
 
Manual da Churrasqueira a Gás de embutir - P
Manual da Churrasqueira a Gás de embutir - PManual da Churrasqueira a Gás de embutir - P
Manual da Churrasqueira a Gás de embutir - P
 
Portfolio Management Categorization Optimization and Re-calibration
Portfolio Management Categorization Optimization and Re-calibrationPortfolio Management Categorization Optimization and Re-calibration
Portfolio Management Categorization Optimization and Re-calibration
 
Idade Moderna
Idade ModernaIdade Moderna
Idade Moderna
 
Medical-PPT
Medical-PPTMedical-PPT
Medical-PPT
 
Acta entrega recepcion de cello
Acta entrega recepcion de celloActa entrega recepcion de cello
Acta entrega recepcion de cello
 

Similar to Libraries

101 2.3 manage shared libraries
101 2.3 manage shared libraries101 2.3 manage shared libraries
101 2.3 manage shared libraries
Acácio Oliveira
 
Working with Shared Libraries in Perl
Working with Shared Libraries in PerlWorking with Shared Libraries in Perl
Working with Shared Libraries in Perl
Ido Kanner
 
SECR'13 Lightweight linux shared libraries profiling
SECR'13 Lightweight linux shared libraries profilingSECR'13 Lightweight linux shared libraries profiling
SECR'13 Lightweight linux shared libraries profiling
OSLL
 

Similar to Libraries (20)

From gcc to the autotools
From gcc to the autotoolsFrom gcc to the autotools
From gcc to the autotools
 
Advanced c programming in Linux
Advanced c programming in Linux Advanced c programming in Linux
Advanced c programming in Linux
 
C++ shared libraries and loading
C++ shared libraries and loadingC++ shared libraries and loading
C++ shared libraries and loading
 
Linkers
LinkersLinkers
Linkers
 
101 2.3 manage shared libraries
101 2.3 manage shared libraries101 2.3 manage shared libraries
101 2.3 manage shared libraries
 
101 2.3 manage shared libraries
101 2.3 manage shared libraries101 2.3 manage shared libraries
101 2.3 manage shared libraries
 
2.3 manage shared libraries
2.3 manage shared libraries2.3 manage shared libraries
2.3 manage shared libraries
 
Embedded Systems: Lecture 13: Introduction to GNU Toolchain (Build Tools)
Embedded Systems: Lecture 13: Introduction to GNU Toolchain (Build Tools)Embedded Systems: Lecture 13: Introduction to GNU Toolchain (Build Tools)
Embedded Systems: Lecture 13: Introduction to GNU Toolchain (Build Tools)
 
Android Variants, Hacks, Tricks and Resources
Android Variants, Hacks, Tricks and ResourcesAndroid Variants, Hacks, Tricks and Resources
Android Variants, Hacks, Tricks and Resources
 
Libraries
LibrariesLibraries
Libraries
 
Development and deployment with composer and kite
Development and deployment with composer and kiteDevelopment and deployment with composer and kite
Development and deployment with composer and kite
 
Composer namespacing
Composer namespacingComposer namespacing
Composer namespacing
 
Livecode widget course
Livecode widget courseLivecode widget course
Livecode widget course
 
Working with Shared Libraries in Perl
Working with Shared Libraries in PerlWorking with Shared Libraries in Perl
Working with Shared Libraries in Perl
 
PHP Dependency Management with Composer
PHP Dependency Management with ComposerPHP Dependency Management with Composer
PHP Dependency Management with Composer
 
SECR'13 Lightweight linux shared libraries profiling
SECR'13 Lightweight linux shared libraries profilingSECR'13 Lightweight linux shared libraries profiling
SECR'13 Lightweight linux shared libraries profiling
 
Autotools pratical training
Autotools pratical trainingAutotools pratical training
Autotools pratical training
 
Composer Helpdesk
Composer HelpdeskComposer Helpdesk
Composer Helpdesk
 
Linkers
LinkersLinkers
Linkers
 
Build Systems with autoconf, automake and libtool [updated]
Build Systems with autoconf, automake and libtool [updated]Build Systems with autoconf, automake and libtool [updated]
Build Systems with autoconf, automake and libtool [updated]
 

Recently uploaded

%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 

Recently uploaded (20)

Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 

Libraries

  • 2. LIBRARIES It is a file containing compiled code that is to be incorporated later into a program. It is of two types: 1. Static library 2. Shared library
  • 3. Static Library ● An archive (or static library) is simply a collection of object files stored as a single file. ● Static libraries end with the ``.a'' suffix. This collection is created using the ar (archiver) program. ● When the linker encounters an archive on the command line, it searches the archive for all definitions of symbols (functions or variables) that are referenced from the object files that it has already processed but not yet defined. ● The object files that define those symbols are extracted from the archive and included in the final executable.
  • 4. Creating a static library ● Compile: gcc -Wall -g -c prog1.c prog2.c -Wall: include warnings -g : include debugging info ● Create library:ar rcs libname.a prog1.o prog2.o ● List files in library: ar -t libctest.a
  • 5.
  • 6. ● Linking with the library: ➢ gcc -o executable-name prog.c libname.a ➢ gcc -o executable-name prog.c -L/path/to/library- directory -lname
  • 7.
  • 8. Shared Library ● A shared library (also known as a shared object, or as a dynamically linked library) is similar to a archive in that it is a grouping of object files. ● The most fundamental difference is that when a shared library is linked into a program, the final executable does not actually contain the code that is present in the shared library. Instead, the executable merely contains a reference to the shared library.
  • 9. Creating a shared library ● Create library: gcc -Wall -fPIC -c prog1.c prog2.c gcc -shared -o libname.so prog1.o prog2.o ● You can create a seperate directory for your shared libraries. Eg /opt/lib where opt is a directory that is reserved for all the software and add-on packages that are not part of the default installation.
  • 10. ● You can move the created shared library to that directory. Eg: mv libname.so /opt/lib ● If you are creating the library with version number eg libname.so.x where x is the version number you have to link the file as shown below. ln -sf /opt/lib/libname.so.x /opt/lib/libname.so ● The link to /opt/lib/libname.so allows the naming convention for the compile flag -lctest to work.
  • 11.
  • 12. ● Compile main program and link with shared object library: gcc -Wall -o prog prog.c -L/opt/lib -lname ● The shared library dependencies of the executable can be listed with the command: ldd name-of- executable eg: ldd prog
  • 13. ● The output of ldd may show something like below: libname.so => not found ● You can fix this by following one of the method below: a) export LD_LIBRARY_PATH=/opt/lib
  • 14.
  • 15. b) During compiling you could add rpath as below gcc -o prog prog.c -L/opt/lib -lname -Wl,-rpath=/opt/lib c) You can add the path of the library in etc/ld.so.conf.d/libc.conf ● To update the cache use sudo ldconfig
  • 16.
  • 17. ● Now if you check the dependencies the not found would have disappeared. ● In LD_LIBRARY_METHOD the environmental variable vanishes once you close the terminal so you have to specify the path again and again ● In rpath the path is added to the executable so you dont have to mention it again for that one.
  • 18. ● If you have added the library path in libc.conf the libraries will be searched there automatically. ● Note: ➢ Suppose that both libname.a and libname.so are available.Then the linker must choose one of the libraries and not the other. ➢ The linker searches each directory (first those specified with -L options, and then those in the standard directories).
  • 19. ➢ When the linker finds a directory that contains either libtest.a or libtest.so, the linker stops searching the directories. ➢ If only one of the two variants is present in the directory, the linkerchooses that variant. ➢ Otherwise, the linker chooses the shared library version, unless you explicitly instruct it otherwise.You can use the -static option to demand static archives. ➢ For example, the following line will use the libname.a archive, even if the libname.so shared library is also available: gcc -static -o prog prog.c -L/opt/lib –lname
  • 20. ● These shared libraries are dynamically linked. ● Even though the dynamic linker does a lot of the work for shared libraries, the traditional linker still has a role to play in creating the executable. ● The traditional linker needs to leave a pointer in the executable so that the dynamic linker knows what library will satisfy the dependencies at runtime. ● The dynamic section of the executable requires a NEEDED entry for each shared library that the executable depends on.
  • 21.
  • 22. ● The dynamic linker is the program that manages shared dynamic libraries on behalf of an executable. ● The essential part of the dynamic linker is fixing up addresses at runtime, which is the only time you can know for certain where you are loaded in memory. A relocation can simply be thought of as a note that a particular address will need to be fixed at load time.
  • 23. ● Shared libraries can also be loaded at times other than during the startup of a program. They're particularly useful for implementing plugins. Eg adobe plugin in browser.. ● To use dynamic loading functions,include the <dlfcn.h> header file and link with the –ldl option to pick up the libdl library.
  • 24. Functions in dynamic loaading ● The dlopen function opens a library void * dlopen(const char *filename, int flag); eg: dlopen("/opt/lib/libname.so", RTLD_LAZY); RTLD_LAZY: If specfied there is no concern about unresolved symbols until they are referenced.
  • 25. RTLD_NOW: All unresolved symbols are resolved when dlopen() is called. ● dlerror() Errors can be reported by calling dlerror(), which returns a string describing the error from the last call to dlopen(), dlsym(), or dlclose(). One point to note is that after calling dlerror(), future calls to dlerror() will return NULL until another error has been encountered.
  • 26. ● dlsym() The return value from the dlopen function is a void * that is used as a handle for the shared library.You can pass this value to the dlsym function to obtain the address of a function that has been loaded with the shared library. ● dlclose() The dlclose function unloads the shared library.
  • 27. ● The executable is created for dynamic loading as below gcc -rdynamic -o progdl progdl.c -ldl ● Thus library is dynamically loaded.
  • 28. #include <stdio.h> #include <stdlib.h> #include <dlfcn.h> #include "ctest.h" int main(int argc, char **argv) { void *lib_handle; double (*fn)(int *); int x; char *error;
  • 29. lib_handle = dlopen("/opt/lib/libctest.so", RTLD_LAZY); if (lib_handle==NULL) { fprintf(stderr, "%sn", dlerror()); exit(1); } fn = dlsym(lib_handle, "ctest1");
  • 30. if ((error = dlerror()) != NULL) { fprintf(stderr, "%sn", error); exit(1); } (*fn)(&x); printf("Valx=%dn",x); dlclose(lib_handle); return 0; }
  • 31. Benefits of Static Libraries ● Static libraries cannot eliminate duplicated code in the system. However, there are other benefits to using static libraries. Some of these benefits are as follows: ● Static libraries are simple to use. ● The static library code does not need to be position-independent code.
  • 32. Benefits of Shared Libraries ● Code sharing saves system resources. ● Several programs that depend on a common shared library can be fixed all at once by replacing the common shared library. ● The environment can be modified to use a shared library. ● Programs can be written to load dynamic libraries without any prior arrangement at link time.