Linux环境下静态库的生成和使用 (.a文件)
??????? 這一陣子的工作用到了linux,也用到了linux的靜態(tài)庫和動態(tài)庫。正好對這一塊兒一直不明白,趁此機會學習了一下。以下是筆記。先說一說linux下靜態(tài)庫的生成和使用方法。
???? An archive (or static library) is simply a collection of object files stored as a single file.(An archive is roughly the equivalent of a Windows .LIB file.) When you provide an archive to the linker, the linker searches the archive for the object files it needs, extracts them, and links them into your program much as if you had provided those object files directly.?
???? You can create an archive using the ar command.Archive files traditionally use a .a extension rather than the .o extension used by ordinary object files. Here’ s how you would combine test1.o and test2.o into a single libtest.a archive:
% ar cr libtest.a test1.o test2.o
???? The cr flags tell ar to create the archive.
???????????????????????????????????????????????? ??????????????????????????? ---摘自《Advanced Linux Programming》
由上面可以看到,linux操作系統(tǒng)中,
1.靜態(tài)庫是一些目標文件(后綴名為.o)的集合體而已。
2.靜態(tài)庫的后綴名是.a,對應于windows操作系統(tǒng)的后綴名為.lib的靜態(tài)庫。
3.可以使用ar命令來創(chuàng)建一個靜態(tài)庫文件。
來看一個實例,根據(jù)書中的代碼簡化的,先看一看可以編譯成庫文件的源文件中的代碼:
代碼非常簡單,只有一句話。我們敲入如下命令:
gcc –c test.c
ar cr libtest.a test.o
會在當前目錄下生成一個libtest.a靜態(tài)庫文件。-c表示只編譯,不鏈接。再來看一看如何使用這個庫。如下代碼:
敲入如下命令:
gcc –c app.c
gcc -o app app.o -L. –ltest
敲命令的時候要記得將libtest.a文件和生成的app.o文件放在同一個目錄(即當前目錄)下。這樣,敲入命令后,會在當前目錄下生成一個名為app的可執(zhí)行文件。-o表示指定輸出文件名。執(zhí)行一下./app,可以看一看結果:
這就是生成linux下面靜態(tài)庫的簡單用法了。
總結
以上是生活随笔為你收集整理的Linux环境下静态库的生成和使用 (.a文件)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C语言的int, float,doubl
- 下一篇: linux基础——linux进程间通信(