Process of Creating a Static Library(.a) in C

We will see how we can create a static library in C.

Now steps for creating a static library for these two files are
Step1: Implement source code for the library

add.c:We have implemented the addition function in the file

int add(int a, int b)
{
     return a+b;
}

sub.c :Implemented the subtraction function in the file

int sub(int a, int b)
{
     return a-b;
}


Step2: Compile the sources into relocatable binaries

gcc -c add.c     O/P: add.o
gcc -c sub.c     O/P: sub.o

Step3: Use archive tool to create a static library image

ar rcs libarith.a add.o sub.o

r  --> replace if existing
c  --> create
s  --> symbol table

libarith,a is the name of the static library and the convention is the library name should start with lib.

Step4: If we want to see what are the files present in the static library

ar -t libarith.a

   (OR)

nm -s libarith.a

Now the library is created, If you want to test this library you have to call the functions in your program and include this library will compiling

app.c:

#include <stdio.h>

int main()
{
   printf("add:%d\t sub:%d\n".add(2,3),sub(2,3));
   return 0;
}

Compile it with the following command:
gcc app.c -o app ./libarith.a

Comments

Popular posts from this blog

bb.utils.contains yocto

Difference between RDEPENDS and DEPENDS in Yocto

make config vs oldconfig vs defconfig vs menuconfig vs savedefconfig