C Static Library? Whatever do you mean?

Colton Walker
2 min readNov 7, 2016

Library as we know it to be is a collection of books basically. In programing this concept is fairly similar. A library is a collection of functions instead of books. When you as a programmer decide to keep your main program clean and clear of much of your functions, you store them in a separate area and call them upon compilation. To access them, we use what is called a header files which normally end in a “.h” and is at the top of your program(This gets used during the preprocessor stage of compiling).

The header file contains the declarations (sometimes called prototypes) of your functions. During the linking stage of compilation, the header file decorations are linked to their respective definitions which live in a “.c” folder and are added directly into your main programs executable file(.exe). This process as a whole is called “static linking”. However, this style of linking can be very taxing to your computers memory. Suppose you have multiple functions you would like to use for other programs, you would need multiple copies of the same function. The “dynamic linking” process prevents this by linking the functions during run-time (unlike static linking which links during compile time).

Let’s talk about the steps needed to make this fantastic link happen. First, take all your function decorations and place it into a “.h” file. Next you will need to place all you function “.c” file in the current working directory to make it easier for compilation. Once, that is complete its necessary to use the GNU compile collection by running “gcc -c *.c”. This tells the computer to target compilation for all c files in the current directory. If nothing happens when you compile the “.c” files then thats good news. It means success! If you “ls” you’ll not only see all the “.c” files but all there object file counter parts ending in “.o”. Lastly, the“.o” files need to be linked into one library that your program’s functions can reference. Lets use the “ar” program that creates, modifies, extracts from archives with a “-rc” flag(“r” stands for replace and “c” to create). Don’t forget to target all your “.o” files with “*.o”. Your code should look like this: “ar -rc LibraryName.a *.0”

After using “ls” you should now be left with a compiles library with all of the specifies functions. The perks of a staticky linked library is that it is portable and can work across other programs, but remember this linking system uses much memory so use wisely!

--

--