Static libraries

  • We will save the time of compiling each time that code that is already compiled. In addition, we already know that while we make a program, we test and correct, it is necessary to compile between many and “more many” times.
  • The already compiled code will be tested and reliable. Not the first few times, but when we have already used it in 200 different programs and we have corrected the errors.

How we have to organize our code

In order to put our code in a library, we need to organize it in the following way:

  • One or more .h header files with the types (typedefs, structs and enums) and prototypes of the functions that we want to be able to use.

Compile and link with static libraries

Once we have our code, to get a static library we must perform the following steps:

  • Create the library (.a). To do this, use the ar command with the following parameters: ar -rv libname.a source1.o source2.o … The -r option tells the ar command that it has to insert (or replace if they are already inside) the files object in the library. The -v option is “verbose”, so it displays information while you’re doing things. Next we put all the object files that we want. ar is actually a much more generic command than all this and can be used to package any type of file (not just object files). It also has options to see what files are inside, delete some of them, replace them, etc.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store