How to Create a Library in C

May 9, 2021 0 Comments

How to Create a Library in C

How to Create a Library in C, Executables can be created in two ways

1. Static: 

They contain fully resolve library functions that physically link to the executable images during building.

creating static libraries:

1. Implement library source files.

How to Create a Library in c

2. compile and generate relocatable files.

gcc add.c -o add.o gcc sub.c -o sub.o

3. use ar tool for creating a static library using all those relocatable files created it step 2

            ar rcs libex.a example.o

To check the number of files in the library use the below command.

ar -t libex.a

How to Create a Library in c

4. All libraries in Linux start with ‘lib’ follow by name and extension is .a they are considered as static libraries. To check the static library let’s write a C program example.c

example.c

How to Create a Library in c

we need to compile example.c with static library.

gcc example.c -o examplestat ./libex.a

How to Create a Library in c

2. Dynamic: 

How to Create a Library in C, They contain symbolic references to library functions use, and these references fully resolve either during application load time or run time.

Load Time Libraries: These libraries will be linked by the linker with executable at link time such libraries get loaded along with the application when application execution is initiated.

Runtime libraries: These libraries will be loaded by the application when needed and unloaded by the application when needed, which are considered runtime libraries.

creating dynamic libraries:

    1. Implement library source files.

How to Create a Library in c

2. compile and generate position Independent relocatable files.

gcc -c -fpic add.c -o add.o

gcc -c -fpic sub.c -o sub.o

-fpic is a flag which use to tell the linker as it is position independent.

3. invoke GCC with -shared flag for creating a shared object.

            gcc -shared add.o sub.o -o libexa.so

4. all libraries in Linux start with ‘lib’ followed by name and extension is .so they consider as dynamic libraries.

we need to compile example.c with dynamic library.

gcc example.c -o exampledyn ./libexa.so

How to Create a Library in c

In both static and dynamic cases the output will be the same, but to understand the differences between static and dynamic, we analyze the executables using objdump tool.

objdump -D examplestat | more

How to Create a Library in c

objdump -D exampledyn | more

How to Create a Library in c

Here in dynamic executable’s main function, it is calling example@plt, (plt= procedure linkage table). Plt table generates by the linker and contains information about dynamic linking.

Share This:

One thought on “How to Create a Library in C”

  1. I enjoy, resᥙlt in I found just what I was having a looҝ fⲟr.
    You’ve ended my four day lengthy hunt! God Bless you man. Have a nice
    day. Bye

Comments are closed.