Linux下調用so庫

開發中通常需要模塊化設計,因此通常獨立的功能會在單獨的模塊中實現,在widnows下通常實現爲dll,而在linux下則封裝成so庫,我們來看一下在ubuntu下怎麼調用so庫。以下代碼與操作在ubuntu12.04上實現。

首先編寫一個簡單的so

 

 

int hello_add(int a, int b)

{

    return a + b;

}

然後將它編譯成.so文件:

$ gcc -O -c -fPIC -o hello.o hello.c

$ gcc -shared -o libhello.so hello.o

放到系統庫中:

# cp libhello.so /usr/local/lib

# sudo ldconfig

在這裏說明一下,之前的linux系統的用戶動態庫目錄設置好像是在/etc/ld.so.conf.d/local.conf文件中,而在我使用的ubuntu12.04中是在/etc/ld.so.conf.d/libc.conf這個文件中,而且默認已設置爲/usr/local/lib這個目錄,將我們的so文件放到這個目錄後,需用ldconfig命令使其生效。

下面我們寫個test程序來驗證一下:

 

#include <stdio.h>

int main()

{

    int a = 3, b = 4;

    printf("%d + %d = %d\n", a, b, hello_add(a,b));

    return 0;

}

編譯並執行:

$ gcc -o hellotest hellotest.c -lhello

$ ./hellotest

3 + 4 = 7

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章