How to Create a library in C

nelavalli satheesh
3 min readMay 17, 2021

--

Executables can be created in two ways

1. Static: They contain fully resolved library functions that are physically linked into the executable images during built.

creating static libraries:

1. Implement library source files.

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 library use below command.

ar -t libex.a

4. All libraries in Linux start with ‘lib’ followed 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

we need to compile example.c with static library.

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

2. Dynamic: They contain symbolic references to library functions used and these references are fully resolved either during application load time or run time.

creating dynamic libraries:

1. Implement library source files.

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 is used 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 are considered as dynamic libraries.

we need to compile example.c with dynamic library.

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

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

objdump -D examplestat | more

objdump -D exampledyn | more

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

For More Information click here

--

--