Static Libraries in C

Cody Paral
2 min readFeb 12, 2018

--

Libraries in C serve a very useful purpose, they allow us to use a large amount of functions so we don’t have to make a function for everything we want to do. On top of that it makes code easy to read because there isn’t a bunch of functions in the program. Having the ability to create libraries can make code smaller and easier to read but still give you access to all the functions your program calls.

Static libraries work by taking the binary of all the functions you will need and links them with the binary of your program in the linking phase. Lets say your program calls the functions _printage(), this function takes the users birth year and the current year and finds their age.

ar will allow you to create an archive. #1 are commands to ar, r means insert the .o files into the library, c means create the library (this helps with warnings if there is no archive), and s adds an index. #2 This is your library name you have to add lib- before the name and an .a after to signify that this is the archive. #3 these are your .o files, there is no limit on the amount of .o files your library can contain. Once you have all the .o files you need you can create a program using the library.

To compile the program you use gcc. #1 this tag is saying that you are compiling a program with a static library. #2 this is the .c file for your program. #3 This tag is saying to look in the current directory for the library that was created in the previous step. #4 this is you library name, you do not put the .a or lib- the compiler is smart enough to find the library by name. #5 this is the name of the program your making.

Sense you add the binary code from the library into the binary code from the program the only thing you need to use the program is the program itself. However because the binary is added into the program after this step your program may become larger in size.

--

--