gcc,c++ 動態庫呼叫靜態庫
生成動態庫: 需要的目標檔案得用-fPIC選項生成.
而靜態庫所需的目標檔案可以不用-fPIC選項.
一個應用程式呼叫動態庫, 而這個動態庫其中的函式呼叫某靜態庫時,如何生成應用程式呢?
例:
/////// 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;
}
方法一:
靜態庫的.o檔案也用-fPIC生成. 生成動態庫時把靜態庫加入.
生成應用程式時只加載動態庫
g++ -c -fPIC static.cpp // 生成static.o
ar -r libstatic.a static.o // 生成靜態庫libstatic.a
g++ -c -fPIC shared.cpp // 生成shared.o
g++ -shared shared.o -lstatic -o libshared.so // 生成動態庫libshared.so 注: -shared是g++的選項,與shared.o無關. -lstatic選項把libstatic.a的函式加入動態庫中.
g++ test.cpp -lshared -o test.exe // link libshared.so 到test.exe中.
方法二:
靜態庫的.o檔案不用-fPIC生成. 生成動態庫時不加表態庫.
生成應用程式時載入動態庫和靜態庫.
g++ -c static.cpp // 生成static.o
ar -r libstatic.a static.o // 生成靜態庫libstatic.a
g++ -c -fPIC shared.cpp // 生成shared.o
g++ -shared shared.o -o libshared.so // 生成動態庫libshared.so 注: -shared是g++的選項,與shared.o無關. 這時如果加-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 到test.exe中.
兩種方法的不同之處在於static_print的實際程式碼一個在.so中.一個在最後test.exe檔案中. 個人覺得第一種方法更好, 因為動態庫應該看成一個可以獨立執行的程式.