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

Self-Hosted Scripting in Guile
Self-Hosted Scripting in GuileSelf-Hosted Scripting in Guile
Self-Hosted Scripting in GuileIgalia
 
Introduction to the LLVM Compiler System
Introduction to the LLVM  Compiler SystemIntroduction to the LLVM  Compiler System
Introduction to the LLVM Compiler Systemzionsaint
 
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
 
嵌入式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 OptimizationVivek Pansara
 
.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)citizenmatt
 
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 Yogesh Salvi
 
Robot operating system [ROS]
Robot operating system [ROS]Robot operating system [ROS]
Robot operating system [ROS]Abrar Mohamed
 
Understanding Implicits in Scala
Understanding Implicits in ScalaUnderstanding Implicits in Scala
Understanding Implicits in Scaladatamantra
 
Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scaladatamantra
 
Indic threads pune12-apache-crunch
Indic threads pune12-apache-crunchIndic threads pune12-apache-crunch
Indic threads pune12-apache-crunchIndicThreads
 
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 ProgramsSam Bowne
 
Java.util.concurrent.concurrent hashmap
Java.util.concurrent.concurrent hashmapJava.util.concurrent.concurrent hashmap
Java.util.concurrent.concurrent hashmapSrinivasan Raghvan
 
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 FlinkAljoscha Krettek
 
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 MalothBhavsingh 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 2019Thomas Weise
 

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

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'sBluewater Learning
 
Práctica 1b
Práctica 1bPráctica 1b
Práctica 1bSara1452
 
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 - PCottage Casa E Lazer
 
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-calibrationProductivity Intelligence Institute
 
Acta entrega recepcion de cello
Acta entrega recepcion de celloActa entrega recepcion de cello
Acta entrega recepcion de celloFREDY GUANDINANGO
 

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 Explained

From gcc to the autotools
From gcc to the autotoolsFrom gcc to the autotools
From gcc to the autotoolsThierry Gayet
 
Advanced c programming in Linux
Advanced c programming in Linux Advanced c programming in Linux
Advanced c programming in Linux Mohammad Golyani
 
C++ shared libraries and loading
C++ shared libraries and loadingC++ shared libraries and loading
C++ shared libraries and loadingRahul Jamwal
 
101 2.3 manage shared libraries
101 2.3 manage shared libraries101 2.3 manage shared libraries
101 2.3 manage shared librariesAcácio Oliveira
 
101 2.3 manage shared libraries
101 2.3 manage shared libraries101 2.3 manage shared libraries
101 2.3 manage shared librariesAcácio Oliveira
 
2.3 manage shared libraries
2.3 manage shared libraries2.3 manage shared libraries
2.3 manage shared librariesAcácio Oliveira
 
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)Ahmed El-Arabawy
 
Android Variants, Hacks, Tricks and Resources
Android Variants, Hacks, Tricks and ResourcesAndroid Variants, Hacks, Tricks and Resources
Android Variants, Hacks, Tricks and ResourcesOpersys inc.
 
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 kiteChristian Opitz
 
Livecode widget course
Livecode widget courseLivecode widget course
Livecode widget coursecrazyaxe
 
Working with Shared Libraries in Perl
Working with Shared Libraries in PerlWorking with Shared Libraries in Perl
Working with Shared Libraries in PerlIdo Kanner
 
PHP Dependency Management with Composer
PHP Dependency Management with ComposerPHP Dependency Management with Composer
PHP Dependency Management with ComposerAdam Englander
 
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 profilingOSLL
 
Autotools pratical training
Autotools pratical trainingAutotools pratical training
Autotools pratical trainingThierry Gayet
 
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]Benny Siegert
 

Similar to LIBRARIES Explained (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

PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 

Recently uploaded (20)

PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 

LIBRARIES Explained

  • 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.