一html
在應用程序須要鏈接外部庫的狀況下,linux默認對庫的鏈接是使用動態庫,在找不到動態庫的狀況下再選擇靜態庫。使用方式爲:mysql
gcc test.cpp -L. -ltestliblinux
若是當前目錄有兩個庫libtestlib.so libtestlib.a 則確定是鏈接libtestlib.so。若是要指定爲鏈接靜態庫則使用:sql
gcc test.cpp -L. -static -ltestlibwindows
使用靜態庫進行鏈接。函數
當對動態庫與靜態庫混合鏈接的時候,使用-static會致使全部的庫都使用靜態鏈接的方式。這時須要做用-Wl的方式:ui
gcc test.cpp -L. -Wl,-Bstatic -ltestlib -Wl,-Bdynamic -ltestdll this
另外還要注意系統的運行庫使用動態鏈接的方式,因此當動態庫在靜態庫前面鏈接時,必須在命令行最後使用動態鏈接的命令才能正常鏈接.net
,如:命令行
gcc test.cpp -L. -Wl,-Bdynamic -ltestdll -Wl,-Bstatic -ltestlib -Wl,-Bdynamic
最後的-Wl,-Bdynamic表示將缺省庫連接模式恢復成動態連接。
二:查看靜態庫導出函數
注意:參數信息只能存在於 .h 頭文件中
windows下
dumpbin /exports libxxx.a
linux 下
nm -g --defined-only libxxx.a
三
場景是這樣的。我在寫一個Nginx模塊,該模塊使用了MySQL的C客戶端接口庫libmysqlclient,固然mysqlclient還引用了其餘的庫,好比libm, libz, libcrypto等等。對於使用mysqlclient的代碼來講,須要關心的只是mysqlclient引用到的動態庫。大部分狀況下,不是每臺機器都安裝有libmysqlclient,因此我想把這個庫靜態連接到Nginx模塊中,但又不想把mysqlclient引用的其餘庫也靜態的連接進來。
咱們知道gcc的-static選項可使連接器執行靜態連接。但簡單地使用-static顯得有些’暴力’,由於他會把命令行中-static後面的全部-l指明的庫都靜態連接,更主要的是,有些庫可能並無提供靜態庫(.a),而只提供了動態庫(.so)。這樣的話,使用-static就會形成連接錯誤。
以前的連接選項大體是這樣的,
1 | CORE_LIBS="$CORE_LIBS -L/usr/lib64/mysql -lmysqlclient -lz -lcrypt -lnsl -lm -L/usr/lib64 -lssl -lcrypto" |
修改過是這樣的,
12 | CORE_LIBS="$CORE_LIBS -L/usr/lib64/mysql -Wl,-Bstatic -lmysqlclient\ -Wl,-Bdynamic -lz -lcrypt -lnsl -lm -L/usr/lib64 -lssl -lcrypto" |
其中用到的兩個選項:-Wl,-Bstatic和-Wl,-Bdynamic。這兩個選項是gcc的特殊選項,它會將選項的參數傳遞給連接器,做爲連接器的選項。好比-Wl,-Bstatic告訴連接器使用-Bstatic選項,該選項是告訴連接器,對接下來的-l選項使用靜態連接;-Wl,-Bdynamic就是告訴連接器對接下來的-l選項使用動態連接。下面是man gcc對-Wl,option的描述,
-Wl,option Pass option as an option to the linker. If option contains commas, it is split into multiple options at the commas. You can use this syntax to pass an argument to the option. For example, -Wl,-Map,output.map passes -Map output.map to the linker. When using the GNU linker, you can also get the same effect with -Wl,-Map=output.map.
下面是man ld分別對-Bstatic和-Bdynamic的描述,
-Bdynamic -dy -call_shared Link against dynamic libraries. You may use this option multiple times on the command line: it affects library searching for -l options which follow it. -Bstatic -dn -non_shared -static Do not link against shared libraries. You may use this option multiple times on the command line: it affects library searching for -l options which follow it. This option also implies --unresolved-symbols=report-all. This option can be used with -shared. Doing so means that a shared library is being created but that all of the library's external references must be resolved by pulling in entries from static libraries
http://blog.csdn.net/lapal/article/details/5482277
http://blog.chinaunix.net/uid-20737871-id-3083925.html