GCC靜態鏈結和動態鏈結

2021-09-01 01:19:42 字數 1922 閱讀 9692

寫在前面:最近因為需要在不同版本的linux上執行編譯後的檔案,經常會遇到找不到需要的鏈結庫檔案的問題,後來突然想起了靜態編譯這一說。

1:建靜態庫

/* hellos.h */

#ifndef _hello_s_h

#define _hello_s_h

void prints(char* str);

#endif

/* hellos.c */

#include "hellos.h"

void prints(char* str)

輸入命令:

gcc -c -o hellos.o hellos.c

ar cqs libhellos.a hellos.o //ar是生成庫的命令,cqs是引數, libhellos.a是生成的靜態鏈結庫須以lib開頭,hellos是庫名,a表示是靜態鏈結庫,hellos.o是剛才生成目標檔案。於是得到了libhellos.a這麼乙個靜態鏈結庫

2:主程式

/* main.c */

#include

#include "hellos.h"

main()

gcc -o hello main.c -static -l. –lhellos

下面是關於上面命令的解釋:

庫依賴使用-i引數可以向gcc的標頭檔案搜尋路徑中新增新目錄。

gcc hello.c -i /home/wuzhiguo/include -o hello

使用-l引數可以向gcc的庫檔案搜尋路徑中新增新目錄。

gcc hello.c -l /home/wuzhiguo/lib -l mylib -o hello

-l mylib 是指示gcc去鏈結庫檔案libmylib.so。linux下的庫檔案有乙個約定,全部以lib開頭,因此可以省去lib。

動態庫:.so結尾,在執行時載入。

靜態庫:.a結尾,在編譯時載入。

預設gcc優先載入動態庫,可以在通過-static選項強制使用靜態鏈結庫。

gcc hello.c -l /home/wuzhiguo/lib -static -l mylib -o hello

所以-l後面的點為當前目錄,-l後面是要靜態連線的庫(libhellos.a)

然後執行hello可以看到輸出

print in static way: hello world!

刪除libhellos.a和hellos.*後, 程式仍然正常執行。

下面再來看動態鏈結

3:建動態庫

/* hellod.h */

#ifndef _hello_d_h

#define _hello_d_h

void printd(char* str);

#endif

/* hellod.c */

#include "hellod.h"

void printd(char* str)

輸入命令:

gcc -shared -o libhellod.so hellod.c

於是得到了libhellod.so這麼乙個動態鏈結庫,然後複製到/lib目錄中,否則執行的時候找不到庫檔案。

4:主程式

/* main.c */

#include

#include "hellod.h"

main()

gcc -o hello main.c -l. -lhellod

然後執行hello可以看到輸出

print in dynamic way: hello world!

如果這時候刪除剛剛生成的libhellod.so,再執行則會報告乙個找不到libhellod.so的錯誤,程式無法正常執行。

gcc -g -lstdc++ -g -wi,-bdynamic -l. -lmy -wi,-bstatic -l. -lmy -o test.exe main.cc

靜態鏈結和動態鏈結

靜態載入dll dll工程b 專案屬性 配置屬性 常規 配置型別 動態庫 dll 在宣告檔案中,宣告匯出函式 declspec dllexport int xx 如果是c檔案,要在c 檔案中被呼叫,註明extern c 可以 ifdef cplusplus extern c endif 呼叫dll的...

靜態鏈結和動態鏈結

1 靜態鏈結庫只包含 lib檔案 動態鏈結庫包含 lib檔案和dll檔案,靜態鏈結庫中不能再包含其他的動態鏈結庫或者靜態庫,而在動態鏈結庫中還可以再包含其他的動態或靜態鏈結庫。此外他們都會用到定義了函式和相關資料結構的.h標頭檔案,其中 h標頭檔案是編譯時必須的,lib是鏈結時需要的,dll是執行時...

靜態鏈結和動態鏈結

動態鏈結庫 靜態庫 import庫區別 windows為應用程式提供了豐富的函式呼叫,這些函式呼叫都包含在動態鏈結庫中。其中有3個最重要的dll,kernel32.dll,它包含用於管理記憶體 程序和執行緒的各個函式 user32.dll,它包含用於執行使用者介面任務 如視窗的建立和訊息的傳送 的各...