Dynamic C Libraries
Introduction
Before starting to talk about the subject matter, let us take a brief look at the compilation phases of a C program.
There are basically four phases:
- Pre-processing
- Compilation
- Assembly
- Linking
In this article, we will focus on the dynamic libraries and their role in the linking phase of a program.
If you want to learn more about a static libraries and compare them, please visit my previous post
But, first of all, let us define a library.
What is a library?
A library is a collection of code routines (functions, classes, variables, and so on) that can be called upon when building our program, so instead of writing the same code over and over again, we can archive it and extract it from something that has already been written and optimized.Why use libraries?
What is a Dynamic library and how do they work?
How to Create a C Dynamic Library on Unix like System
gcc -fPIC -c my_math_func.c print_alphabet.cmy_math_func.o print_alphabet.ogcc -shared my_math_func.o print_alphabet.o -o libname.soThis command creates a dynamic library named "libname.so" and puts copies of the object files "my_math_func.o" and "print_alphabet.o " in it.
Flag description:
-shared: Produce a shared object which can then be linked with other objects to form an executable.
-o: To define output shared object name.
In order to list the names of the object files in our library, we can use the nd command with -D flag:nm -D --defined-only libname.soFlag description:
-D: Display the dynamic symbols rather than the normal symbols. This is only meaningful for dynamic objects, such as certain types of shared libraries.
--Defined-only: Display only defined symbols for each object file.
How to use them?
void print_alphabet(void);
int main(void)
{
print_alphabet();
return (0);
}gcc main.c -L. -llibname -o mainexport LD_LIBRARY_PATH=<path_to_my_dyn_lib/>:$LD_LIBRARY_PATH$./main
abcdefghijklmnopqrstuvwxyz

Comentarios
Publicar un comentario