linux下動態庫的編寫和調用,linux動態庫編寫

來源:互聯網
上載者:User

linux下動態庫的編寫和調用,linux動態庫編寫

linux下動態庫的編寫和調用

  linux下編寫和調用一個簡單的動態庫大概分為以下幾個步驟:

  • 建立動態庫程式檔案
    add.c
int add(int a,int b){    return a+b;}
  • 建立引用標頭檔
    head.c
#ifndef _HEAD_#define _HEAD_int add(int a,int b);#endif
  • 產生目標檔案
    產生要加編譯器選項 -fpic
gcc -fpic  -c  add.c
  • 然後產生動態庫
    注意使用連結器選項 -shared
gcc  -shared –o  libhead.so  add.o
  • 編寫主程式進行調用
    main.c
#include <stdio.h>#include "head.h"int main(void){    printf("3+5 sum = %d \n",add(3,5));    return 0;}
  • 產生可執行檔並連結庫檔案
    編譯器時,使用動態連結程式庫和靜態庫是一致的,使用”-l庫名”的方式。
 gcc -o  main  main.c -L  ./  -lhead

  -L指定動態連結程式庫的路勁,-ldXX連結庫函數XX。-lXX是動態庫的調用規則。Linux系統下的動態庫命名方式是lib*.so,而在連結時表示位-l*,*是自己命名的庫名。

  • 報錯解決
error while loading shared libraries: libhead.so:  cannot open shared object file: No such file or directory

  這是因為程式運行時沒有找到動態連結程式庫的原因,注意linux不會自動在目前的目錄尋找動態庫檔案。解決方案一般有三種,借鑒部落格園SmartVessel原文:

(1.) 用ln將需要的so檔案連結到/usr/lib或者/lib這兩個預設的目錄下邊

ln -s /home/使用者名稱/code/lib/*.so  /usr/libsudo ldconfig

  注意填寫你的動態庫所在目錄的路徑,若不知道可以用pwd查看全路徑。如果路徑不對,可能會報錯:

cannot open shared object file: Error 40

(2.) 修改LD_LIBRARY_PATH

export LD_LIBRARY_PATH=/home/使用者名稱/code/lib/:$LD_LIBRARY_PATHsudo ldconfig

(3.) 修改/etc/ld.so.conf,然後重新整理

vim /etc/ld.so.confadd /home/使用者名稱/code/lib/sudo ldconfig

  必須記得更新sudo ldconfig,否則還是會報錯。

  • 運行測試
./main3+5 sum = 8

  好啦,測試成功,有問題可以留言討論!

著作權聲明:本文為csdn博主[applebite](http://blog.csdn.net/applebite)原創文章,轉載請註明出處,侵權必究。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.