Static Libraries in C

Credits: https://iconos8.es/icon/40670/c-programaci%C3%B3n

Kind of libraries

  • Static libraries resist vulnerability because it lives inside the executable file.
  • The speed at run-time occurs faster because its object code (binary) is in the executable file. Thus, calls made to the functions get executed quicker.
  • Changes made to the files and program require relinking and recompilation.
  • File size is much larger.
Credits: https://medium.com/@StueyGK/what-is-c-static-library-fb895b911db1

How to create static libraries in C

  1. Create a C file that contains functions in your library.
  2. Create a header file for the library, for example you can create
    $ vim mylib.h
  3. Compile library files.
    $ gcc -c mylib.c -o mylib.o
  4. Create static library. This step is to bundle multiple object files in one static library (see ar for details). The output of this step is static library.
    $ ar rc mylib.a mylib.o
    The ar” stands for archive and it is used to create the static library. All the files ending in .o will be added to the mylib.a library and they are the object files in this case.
    The
    -rc flag will do two things: replace and create a new library if it does not exist already.
  5. The next step is indexing, to do that, we type:
    $ranlib
    mylib.a
  6. Now our static library is ready to use. At this point we could just copy mylib.a somewhere else to use it. For demo purposes, let us keep the library in the current directory.

How to use static libraries in C

gcc main.c -L -l<filename>

--

--

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