DEV Community

Abdullah-fy
Abdullah-fy

Posted on

static library in c

At first we need to remember how how our code compiling

Image description

in this image i want you to notice that in linker stage merges
static library with your code

what is libraries?
libraries :- are a collection of objects that are made available for use by other programs.

they are pre-compiled function that are not excutable but used at runtime or compile time

there is two type of libraries
1- static library
2- dynamic(shared) library

we will take about static library

it should end with .a (a stand for archive) and start with lib

used for function that are used frequently to void repetation

or for re-distribution from you or a third part and use when we work in big project it will make it easier

any changes made in it will not add till you make compile again(it is one of the differance between it and dynamic library)

anything linked from it compiled directly into final object

1- we need to compile our source code
gcc -c my_file.c -o my_file.o

2-use ar command to create your static library
ar -rc lib_my_library.a my_file.o

if you have more than one object file and want them all you can use
ar -rc lib_my_library.a *.o

ar ==> stand for archive and rc ==> to replace or create this library if not exist

then we need this library to be indexed it will help the compiler to quickly reference sumbols, so we use ranlib

ranlib lib_my_library.a

we can only make add this step to the first one like this

ar -rsc lib_my_library.a *.o

you can see the symbol in library use nm command

nm lib_my_library.a

here we created our library we need to link it

gcc -o name_of_the_file_will_we_run our_main_file.o -L. lib_my_library.a

-L ==> tell the linker that the library in our current directory
-l ==> used to link a specific library to the program it followed by the name of the library without the "lib" and the ".a"

For example, to link the "math" library, you would use the option "-lm".

so lets make an example
i will make to files one of them to multible and the other do division

i will call the first one mult.c
and this the the code in it

Image description

and other file to division and will call it div.c

Image description

and this the code int it

then we need to compile these files so we use this code

Image description
it is fine if you did not use -c but it would be better to do it

then we use our code to create static library

Image description
after this we create our main function

Image description
i added my prototype in the header.h file, here it is
Image description
you can add them directly
then compile the main function

Image description

then link the main function and our static library

Image description

and i will run my main function

Image description
now it is working
if you want to change any number you need to compile your code again as we said before

hope it helped

Top comments (0)