When we write a program need to call the library function, in the program code to add the header file containing the library function declaration, the compiler and linker according to the header file will be written by our program code and library function is located in the library file, build the executable file.
The simplest library of functions can be seen as a "collection" of some target files.
0. Creation of two function source files
1 #include <stdio.h>23void text1 (int a)4{ 5 printf ("%d", a); 6 }
View Code
1 #include <stdio.h>23void text2 (char *str)4 {5 6 printf ("%s", str); 7 }
View Code
1. Compile two function source files into the target file, respectively.
gcc -C text1.c text2.c
.
2. Create a header file with two function declarations
1 /* This is lib.h. It declares functions2*/34void text1 (int ); 5 void Text2 (char *);
View Code
3. Write a test program, the program calls two test functions
1 #include <stdio.h>2"lib.h"34int Main () 5 {6 Text1 (1)'7 text2 ("Hello world\n") 89 }
View Code
4. Compile to target file, explicitly link the target file of the calling function
gcc -o text.o-c text.cgcc -o text text.o text1.o text2.o. /text
5. Assemble the generated two function target files together to generate a library of functions
ar crv libtext.a text1.o text2.o
6. Generating a table of contents for a function library
Ranlib LIBTEXT.A
7. The test program file to display the link function library to generate the executable (otherwise the compiler will go to the standard C library to find links)
You can also use-l to access the library because the library is not placed in the standard location-L path-l=lib
At this point we have completed a library of our own libtext.a, and tested it.
Linux preliminary programming-creating a static function library