Static library on Linux, in fact, is the target archive files.
To create a static library on Linux as follows:
Write source files, object files generated by gcc -c xxx.c.
Ar archive with a target file, generate static library.
With static libraries, write a function using a static library header files.
When using a static library that contains the corresponding header file in the source code, remember to link your own libraries when linking.
The following specific examples to explain through.
Write source file, object file is generated.
The first source file my_print.c
#include < stdio.h>
void cout (const char * message)
fprintf (stdout, "% s \ n", message);
Source File 2: my_math.c
int add (int a, int b)
return a + b;
int subtract (int a, int b)
return a - b;
Using gcc, object file is generated for both the source file:
gcc -c my_print.c my_math.c
We get my_print.o and my_math.o.
Archive object file to obtain a static library.
We use ar target file archiving:
ar crv libmylib.a my_print.o my_math.o
We get libmylib.a, this is what we need static library.
The above command is ar crv command options:
c If you need to generate a new library file, not warnings
r replace the existing library files or insert a new file
v Output details
By ar t libmylib.a you can view the target file libmylib.a included.
More help can be viewed by ar --help.
Note: File names we want to generate a library must be shaped like libxxx.a, so when we link this library, you can use -lxxx.
Conversely, when we tell the compiler -lxxx, the compiler will search in the specified directory libxxx.a or libxxx.so.
Generate the corresponding header file
Libmylib.a header file defines the interface, that is, tell the user how to use libmylib.a.
Generate my_lib.h, which reads as follows:
int add (int a, int b);
int subtract (int a, int b);
void cout (const char *);
Test our static library
In the same directory, the establishment test.c:
int main (int argc, char * argv )
int c = add (15, -21);
cout ( "I am a func from mylib ...");
This source file references libmylib.a the cout and add functions.
gcc test.c -L. -lmylib
Will generate a.out, you can run the program by ./a.out. Static library that we can work properly.
The above command -L. To tell gcc search link library that contains the current path, -lmylib tell gcc when the executable program to link libmylib.a.
By makefile Automation
The above steps are cumbersome, or write a simple makefile it reads as follows:
.PHONY: Build test
libmylib.a: my_math.o my_print.o
ar crv $ @ my_math.o my_print.o
gcc -c my_math.c
gcc -c my_print.c
gcc test.c -L. -lmylib
After written makefile, will run make build libmylib.a build, run make test will generate links libmylib.a program.
If you use a method of generating mingw, on Windows and Linux static library is the same.