Let's Talk about Static libraries.

Let's Talk about Static libraries.

What are Static libraries?

The?most straightforward way of using a library function is to have the object files from the library linked directly into your final executable, just as with those you have compiled yourself. When linked like this the library is called a?static?library, because the library will remain unchanged unless the program is recompiled. This is the most straightforward way of using a library as the final result is a simple executable with no dependencies.

Why use libraries?

Similar to the real-life, a library is a set of books, but in the programming field, a library is a set of functions, variables, or routines. It is very common to code several times the same function such as a part of the process of compilation of a program. that process is unuseful because we can most time code the whole program, even we can destroy our code. In those cases, libraries could be useful because they allow call the functions many times without coding the code again and it could reduce the space in memory.

How do they work?

A static library is purely a collection of?.o?files, put together in an archive that's something like a zip file (with no compression). When you use it for linking, the linker will search the library for?.o?files that provide any of the missing symbols in the main program and pull in those?.o?files for linking, as if they had been included on the command line like?.o?files in your main program. This process is applied recursively, so if any of the?.o?files pulled in from the library have unresolved symbols, the library is searched again for other?.o?files that provide the definitions.

How to create them?

To create a static library first you need to use?gcc?with the option?“-c”?and the .c file that you wish to add to the library:

gcc -c my_lib.c

This will create an archive with “.o” extension, that we will need to pass over to “ar”, a command that handles the creation, modification, and extraction of archive files:

ar -rc my_lib.a my_lib.o

This will result in a static library file that we can use at will in any other C project without needing to know or modify its source code.

How to use them?

When the library is created, you can reference for to run a program. For example:

No alt text provided for this image


要查看或添加评论,请登录

社区洞察

其他会员也浏览了