Program for which Library is created
Library Contains code to multiply two integers.
Header file contains Function Declaration.
find_mul.h
int multiply(int, int);
Source file contains Function Definition
find_mul.c
int multiply(int a, int b)
{
return (a * b);
}
Creating Static Library
A static library is a set of object files that were copied into a single file. This single file is the static library. Executable contains static Libraries at compile time itself. The static file is created with the archiver (ar).
we create object file for find_mul.cpp
gcc -c find_mul.c -o find_mul.oNote: the library must start with the three letters lib and have the suffix .a
and Static Library is
ar rcs libmul.a find_mul.o
Creating a Shared Library
Shared Libaries need position independent code which is done by -fPIC
gcc -c -fPIC find_mul.c -o find_mul.o
and Shared Library is
gcc -shared -o libmul.so find_mul.o
Sample Program Using Library
main.c
#include
#include "find_mul.h"
int main()
{
int a = 20;
int b = 30;
printf("Multplication is %d\n", multiply(a, b));
return 0;
}
Linking against static Library
gcc -static main.c -L. -lmul -o statically_linkedLinking against static Library
For Running
$ ./statically_linked
For Running,
gcc main.c -o dynamically_linked -L. -lmul
$ LD_LIBRARY_PATH=.
$ ./dynamically_linked
Thanks to web.
@kova
No comments:
Post a Comment