1. 程式人生 > >What are static libraries in “C” ?

What are static libraries in “C” ?

How do you create a static library?

The first step is to run our C-files through the GCC compiler to create the corresponding object code files ending with the.o extension using the * wildcard and pathname expansion to do the operation on all .c files.

Next, we use the -c flag on gcc to run the files through the compiler up to the linking stage.

gccall -c *.c

note: gccall is my custom alias for the following flags:

  • Wall
  • Pedantic
  • Werror

Next, use the ar command to create an archive.

To create a static library named scratch with all of the object files in our working directory, we would use the following command:

ar -rc libscratch.a *.o

This creates the static library named libscratch.a

and inserts the (copies of) object files inside of it.

  • the -c flag specifies to create the library if it doesn’t already exist.
  • the -r flag replaces old copies of object files with newer files if the file has been updated.

The next step is indexing, which is what speeds up linking and has the unique feature of being position independent in said library. To ensure indexing of a static library, use the following command — ranlib

. Even though ranlibis embedded into the ar command it is still good practice to run this command since some dependencies (such as not having up to date packages) can cause not using ranlib to create issues.

ranlib libscratch.a

On another note you can use the command nmto look at the contents inside of a library. This is similar to the ‘cat’ command in that it displays the contents inside of the file.

And there you have it, you’ve pretty much learned the TL;DR on static libraries. If you want to learn more I suggest looking through YouTube and StackOverflow.