Linux下編寫簡單的動態連結程式庫

來源:互聯網
上載者:User

(1)Linux下編寫動態連結程式庫。通常靜態連結庫是編譯的時候和源檔案一起編譯產生可執行檔的。動態連結程式庫則不是,它是一個已經編譯好的檔案(靜態則不是),只有當程式啟動並執行時候(但是編譯的時候要將動態連結程式庫的資訊載入進來),它才去找動態連結程式庫拿它想用的一些函數。而且動態連結程式庫可以提高通用性,編寫一個動態連結程式庫可以讓很多人一起用。有點類似類?

test_so.h

#ifndef _TEST_SO_H#define _TEST_SO_H #include <stdio.h>#include <stdlib.h> void test_a();void test_b();void test_c(); #endif

test_a.c

#include "test_so.h" void test_a(){    printf("this is test_a()\n");}

test_b.c

#include "test_so.h"void test_b(){    printf("this is test_b()\n");}

test_c.c

#include "test_so.h"void test_c(){    printf("this is test_c()\n");}

然後將這些檔案編譯為動態連結程式庫gcc test_a.c test_b.c test_c.c --shared -fPIC -o libtest.so,則產生libtest.so檔案(它已經編譯好了),和普通可執行程式不同,它並沒有main()。

在看如何調用它

編寫test.c

#include "test_so.h" int main(void){    test_a();    test_b();    test_c();    return 0;}

gcc test.c -L . -ltest -o test ((-L .)表示動態連結程式庫在本目錄, (-ltest)表示動態連結程式庫的名字為lib(test).so)。

然後通過ldd ./test查看有哪些動態連結程式庫和可執行程式有關聯。

結果發現libtest.so沒有關聯。

運行./test出現:

./test: error while loading shared libraries: libtest.so: cannot open shared object file: No such file or directory

也就是說找不到這個動態連結程式庫,但是我們已經在編譯test.c的時候加入路徑了?

這時候修改LD_LIBRARY_PATH變數

#vim ~/.bashrc添加:LD_LIBRARY_PATH = $LD_LIBRARY_PATH:/home/xxx/Testexport LD_LIBRARY_PATH退出以後#source ~/.bashrc

或者/etc/ld.so.conf添加動態連結程式庫的路徑。

#vim /etc/ld.so.conf添加一行:/home/xxx/Test然後重新整理一把#/sbin/ldconfig -v再編譯執行成功。

 

 

 

 

相關文章

聯繫我們

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