Dynamic library invocation static library example
- 2020-05-07 20:45:26
- OfStack
Generate dynamic libraries: the required target files are generated using the -fPIC option.
The target files required for the static library can be used without the -fPIC option.
Ex. :
/////// static.h
void static_print();
///////static.cpp
#include <iostream>
#include "static.h"
void static_print() {
std::cout<<"This is static_print function"<<std::endl;
}
////// shared.h
void shared_print();
////// shared.cpp
#include <iostream>
#include "shared.h"
#include "static.h"
void shared_print() {
std::cout<<"This is shared_print function";
static_print();
}
////////test.cpp
#include "share.h"
int main()
{
shared_print();
return 0;
}
Method 1:
The.o file for the static library is also generated with -fPIC. Add the static library to the dynamic library.
loads only dynamic libraries when it generates applications
g++ -c -fPIC static.cpp // generate static.o
ar -r libstatic.a static.o // Generate static library libstatic.a
g++ -c -fPIC shared.cpp // generate shared.o
g++ -shared shared.o -lstatic -o libshared.so // Generate dynamic library libshared.so note : -shared is g++ The option to , with shared.o Has nothing to do . -lstatic The options libstatic.a Is added to the dynamic library .
g++ test.cpp -lshared -o test.exe // link libshared.so to test.exe In the .
Method 2:
static library.o file is not generated by -fPIC.
Dynamic and static libraries are loaded when the application is generated.
g++ -c static.cpp // generate static.o
ar -r libstatic.a static.o // Generate static library libstatic.a
g++ -c -fPIC shared.cpp // generate shared.o
g++ -shared shared.o -o libshared.so // Generate dynamic library libshared.so note : -shared is g++ The option to , with shared.o Has nothing to do . So if I add -lstatic. error:relocation R_X86_64_32 against `a local symbol' can not be used when making a shared object; recompile with -fPIC
g++ test.cpp -lshared -lstatic -o test.exe // link libshared.so to test.exe In the .
The difference between the two methods is that the actual code for static_print is 1 in.so and 1 in the final test.exe file.