Photo by Fabian Grohs on Unsplash

C has two different types of libraries: a static library, and a shared library. Libraries are great for massive programs, since a large program would take a very long to compile and link. Having a library chops up the program into smaller chunks of source code to reduce overall compilation and linking time. This blog will be going through a static library; which one of the tools that the compiler supplies, and is just a collection of object files that are linked into the program during the linking phase of compilation. These object files are small units of source code that are related to the program.

Creating a static library: To create a static library, you first need to use the archiver: . is the archiver command, and this code has 2 flags: is for replacing older object files in the library with newer ones, and is for creating the library if it doesn’t already exist. After the flags, you give the library a name along with it’s extension (in this case, it is ). Following the name are the object files that you want to store in the library. To create these object files, you will need to run the command along with the flag, and following the source code files that you want to make into an object files. So an example of this would be: .

After creating the archive, we need to index it. The index is used by the compiler to speed up symbol-lookup inside the library. To index, an example code would be: . The command for indexing is , following the library file.

How to use our indexed library: as mentioned in my previous blog about running ; in the compiling process, object code and libraries are passed through the linker to create an executable file. So the flags for adding libraries into your executable is: . The tells the linker that libraries might be found in the given directory ( here is referring to the current directory. After that, the is for adding the specific library name (note that “lib” and .a extension are omitted when using this flag). So the example code would be: . This code will create an executable called (by default) that has the library linked to it. Any functions from are now usable in .

Software Engineer living in Tokyo | Linux | Cats | https://github.com/kai-dg | https://haruspace.dev | https://ko-fi.com/harukai

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