First of all, C + + compilation process
- Compile: Check the statement symbol definition, and generate the intermediate language for C + + code translation.
- Link: Consolidate intermediate code to generate executable binary code.
Simply put, the library file is a special intermediate language file, the static library is also a special format of the archive file (packaged files).
To use a static library:
1. Write Library functions First
1 #ifndef _print_test_h_2 3 #define_print_test_h_4 #ifdef __cplusplus5 extern "C"6 {7 #endif8 9 extern inttest_a;Ten extern voidprint_test (); One extern voidprint_data_a (); A - #ifdef __cplusplus - } the #endif - - #endif
print_test.h
1 #ifdef __cplusplus2 extern "C"3 {4 #endif5 6#include <stdio.h>7 8 voidprint_test ()9 {Tenprintf"print_test\n"); One } A - intTest_a =0; - voidprint_data_a () the { -printf"data in Libtest test_a =%d\n", test_a++); - } - + - #ifdef __cplusplus + } A #endif
print_test.c
2. Main function file
1#include"print_test.h"2 3 intMain ()4 {5 print_test ();6 print_data_a ();7 print_data_a ();8 print_data_a ();9 print_data_a ();Ten print_data_a (); One return 0; A}
main.c
3. Compiling library functions
4. Packaging Library
5. Compiling the main function and running
tips: Static library file naming usually starts with Lib, and the library is linked directly to the-L library name .
The advantage of a static library is that once the build target (main) is compiled, it is a separate binary file, regardless of its operating environment.
Working with Dynamic libraries
1. Compiling the Library
PS: Oddly enough, dltest.so is given the ability to execute.
2. Compiling the main function
Tips: It is best to put the dynamic link you want to use the default library directory, or run directory without the corresponding library file will be error.
The advantage of a dynamic library is that the target is smaller, and when the library file is updated, the target can continue to run and be updated with the library as long as the original symbolic address is not changed. The update of the dynamic library can be done independently of the target updates.