C static libraries

Luis Reyes
2 min readMar 4, 2021

Why use libraries ?

Library is simply a collection of functions which can be added to your application and the functions called as necessary, just like any other functions in the application. More precisely any object, not only functions can be stored in a library, but the vast majority of libraries only contain functions.

How they work ?

Just in case you need a refresher: Libraries are just files with a bunch of functions in them.

So the first thing you should know is the difference between a static library and a dynamic (shared) library. They’re both useful for different things.

Static libraries are better for quickly getting a library up and running, but it also has drawbacks. It gets compiled into every program that uses it. This means you have to manually update every program that uses it when you edit your library. Not fun!

How to create them ?

  • First thing you must do is create your C source files containing any functions that will be used. Your library can contain multiple object files.
  • After creating the C source files, compile the files into object files.
  • To create a library:
  • ar rc libmylib.a objfile1.o objfile2.o objfile3.o
  • This will create a static library called libname.a. Rename the “mylib” portion of the library to whatever you want.
  • That is all that is required. If you plan on copying the library, remember to use the -p option with cp to preserve permissions.

How to use them ?

  1. declaring the function (prototype provided in the include file)
  2. call the function (with parameter passing of values)
  3. define the function (it is either defined in the header file or the linker program provides the actual object code from a Standard Library object area)

Language Example

C++ #include <cmath>
std::abs(number);
C# Math.Abs(number);
Java Java.lang.Math.abs(number)
JavaScript Math.abs(number);
Python abs(number)

Swift abs(number)

--

--