Linux static link Library [go]
Sometimes we need to compile a set of code into a library to facilitate reuse. For example, the STL and system functions we call are provided in this way. In addition, when a project is large, you sometimes need to create your own link library to make it modular and convenient.
The link library can be divided into dynamic link library and static link library based on the link method. This article describes how to create a static link Library.
Take a simple code as an example. here there are two files main. c and stack. c. Here we plan to use stack. c as a lib for main. c to call.
| 123456789101112131415161718192021222324252627 |
/* Stack. c */charstack [512]; inttop =-1; charpop (void) {returnstack [top --];} voidpush (charc) {stack [++ top] = c ;} /* main. c */# include Charpop (); voidpush (charc); voidmain (void) {push ('A'); push ('B'); printf ("% c \ n ", pop ());} |
To compile stack. c into lib, perform the following two steps:
Use the gcc-c command to compile stack. c into stack. o.
Use the ar command to encapsulate stack. o into libstack.
| 12 |
Gcc-c stack. c ar cr libstack. a stack. o |
After the two commands are executed, you can generate a libstack. a file, and then directly use this. a file to generate an execution file.
| 1 |
Gcc-o run main. c-L.-lstack |
There is not much to introduce in this link command. the-L and-l parameters are used to specify the link Library, which has been described in the previous article.
In the above process, an ar command was used. Ar is the abbreviation of archive, that is, archive. we usually use another archive command tar. The functions of ar and tar are similar, but the ar command performs some extra processing. it Will index the symbols in the target file to be archived. when it is linked to the application, the created indexes will reclaim the link process.
The ar command has many parameters. if only the lib Library is created, only the combined parameters cr are used. This command can accept multiple input files and merge them into a single database.
Ar cr libtest. a first. o second. o third. o
After creating a lib through ar, you can run the ar-t command to check which. o files are packaged in the lib.
Tianfang> ar-t libstack.
Stack. o
In addition, you can use the nm command to view more information such as the symbol table.
| 1234567 |
Tianfang> nm libstack. a stack. o: 00000000 T pop 0000001b T push 00000200 C stack 00000000 D top |
Ar and nm have more command parameters. For more information, refer to this article: how to use AR and NM commands.
Finally, after knowing that ar is just a packaging function, let's look back at the static link Process. In fact, it is just a bunch. o files are packaged into one. file a, the link is still from. file. o file links are essentially different from the previous compilation method.