依賴靜態庫,編譯生成動態庫
阿新 • • 發佈:2018-12-31
如需轉載請註明出處!
直入主題,目標是依賴靜態庫,編譯動態庫,最終生成二進位制檔案。
檔案目錄如下:
檔案內容組織:
add.c
#include "add.h"
int add(int a, int b) {
int c = a + b;
return c;
}
add.h
#ifndef __ADD__
#define __ADD__
int add(int a, int b);
#endif
mymath.c
#include "mymath.h" #include "add.h" int func_add(int a, int b) { int c = 0; c = add(a, b); return c; }
mymath.h
#ifndef __MYMATH__
#define __MYMATH__
int func_add(int a, int b);
#endif
main.c
#include <stdio.h>
#include "mymath.h"
int main(int argc, char* argv[]) {
int a = 1;
int b = 2;
int c = 0;
c = func_add(a, b);
printf("result = %d\n", c);
return 0;
}
接下來,我們執行編譯連結步驟。
接著,我們按照傳統編譯生成動態庫檔案的編譯連結方式依賴libadd.a生成libmymath.so, 並通過nm檢視生成結果:
可以看出來,並沒有任何我們定義的函式資訊。
我們給出解決方法:通過使用 -Wl,--whole-archive 和 -Wl,--no-whole-archive來將靜態庫發包成動態庫:
可以看到,我們定義的func_add出現在符號表。
最後我們通過依賴libmymath.so編譯生成可執行檔案來測試結果:
參考引用:
http://stackoverflow.com/questions/7935421/linking-archives-a-into-shared-object-so