linux下 編譯和使用靜態庫__linux

來源:互聯網
上載者:User

建立並使用靜態庫

第一步:編輯源檔案,test.h test.c main.c。其中main.c檔案中包含main函數,作為程式入口;test.c中包含main函數中需要用到的函數。

vi test.h test.c main.c

第二步:將test.c編譯成目標檔案。

gcc -c test.c

如果test.c無誤,就會得到test.o這個目標檔案。

第三步:由.o檔案建立靜態庫。

ar rcs libtest.a test.o

第四步:在程式中使用靜態庫。

gcc -o main main.c -L. -ltest

因為是靜態編譯,產生的執行檔案可以獨立於.a檔案運行。

第五步:執行。

./main

樣本四 建立並使用動態庫

第一步:編輯源檔案,test.h test.c main.c。其中main.c檔案中包含main函數,作為程式入口;test.c中包含main函數中需要用到的函數。

vi test.h test.c main.c

第二步:將test.c編譯成目標檔案。

gcc -c test.c

前面兩步與建立靜態庫一致。

第三步:由.o檔案建立動態庫檔案。

gcc -shared -fPIC -o libtest.so test.o

第四步:在程式中使用動態庫。

gcc -o main main.c -L. -ltest

當靜態庫和動態庫同名時,gcc命令將優先使用動態庫。

第五步:執行。

LD_LIBRARY_PATH=. ./main

樣本五 查看靜態庫中的檔案

[root@node56 lib]# ar -t libhycu.a

base64.c.o

binbuf.c.o

cache.c.o

chunk.c.o

codec_a.c.o

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.