一、平台版本
Linux版本:Lubuntu14.04
eclipse版本:Oxygen 4.7
二、創建動態庫
1、創建工程:File->New->C/C++ Project,選擇C Managed Build
2、輸入項目名,Project type選Shared Library->Empty Project,工具鏈選用Linux GCC
3、新建源文件,New->Soure File,編寫動態庫代碼(這里是簡單測試因此沒有創建頭文件,可以另建目錄放置源文件和頭文件方便管理)
/* * test.c * * Created on: 2019年1月15日 * Author: */ #include <stdio.h> void test() { printf("hello\n"); }
4、勾選-fPIC,右鍵項目工程->Properties->C/C++ Build->Settings,Tool Settings->GCC C Comoiler->Miscellaneous,勾選Position independent Code(-fPIC)
作用(參考http://blog.sina.com.cn/s/blog_54f82cc201011op1.html):
5、編譯工程,在構建項目工程路徑下的./Debug中可以看見生成的.so文件
三、使用動態庫
1、創建新工程,並設置要使用的庫的名稱和路徑
2、添加代碼,編譯運行
#include <stdio.h> #include <stdlib.h> int main(void) { test(); //動態庫中的函數 return EXIT_SUCCESS; }
運行時候出現以下錯誤:
/home/oyqj/eclipse-workspace2/useTest/Debug/useTest: error while loading shared libraries: libtest.so: cannot open shared object file: No such file or directory
原因:
系統沒有找到對應的庫文件
解決方法(參考https://blog.csdn.net/shine_journey/article/details/78356063):
1、打共享庫放到/usr/local/lib目錄下(很多開源共享庫都會安裝到該目錄)
2、修改共享庫配置文件/etc/ld.so.conf,修改成以下內容
include /etc/ld.so.conf.d/*.conf /usr/local/lib
3、執行命令,告知系統共享動態庫
ldconfig
再次運行程序,成功使用動態庫