首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

GCC 動態鏈接庫構建完整指南:從源碼到 .so 生成與調用實戰

     編輯:關於C語言

動態庫構建全流程

1. 準備源碼文件

頭文件 test.h:

#include <stdio.h>
void first();
void second();
void third();

實現文件:

// first.c
#include "test.h"
void first() { printf("this is first.\n"); }

// second.c
#include "test.h"
void second() { printf("this is second.\n"); }

// third.c
#include "test.h"
void third() { printf("this is third.\n"); }

2. 編譯生成 .so

gcc first.c second.c third.c -fPIC -shared -o libtest.so
  • -fPIC:生成位置無關代碼,支援共享庫加載到任意地址
  • -shared:指定輸出為共享庫而非可執行文件
  • 命名慣例:lib.so

3. 編寫調用程序

// test.c
#include "test.h"
void main() {
    first();
    second();
    third();
}

4. 編譯鏈接可執行文件

gcc test.c -L. -ltest -o test
  • -L.:指定庫搜索路徑為當前目錄
  • -ltest:按慣例查找 libtest.so

5. 運行與常見問題解決

./test
# 輸出:
this is first.
this is second.
this is third.

錯誤: error while loading shared libraries: libtest.so: cannot open shared object file

方案一:配置 ld.so.conf

echo "/your/lib/path" | sudo tee /etc/ld.so.conf.d/test.conf
sudo ldconfig

方案二:創建軟鏈接

ln -s /your/lib/path/libtest.so /usr/lib/

方案三:設置環境變量 (臨時)

export LD_LIBRARY_PATH=/your/lib/path:$LD_LIBRARY_PATH

進階補充

  • 版本控制:libtest.so.1.0.0 + soname + 符號鏈接鏈
  • 符號可見性:-fvisibility=hidden + __attribute__((visibility("default"))) 導出控制
  • C++ 混合編程:頭文件用 extern "C" 防止名字修飾
  • 調試技巧:ldd test 查看依賴、nm -D libtest.so 列導出符號

掌握動態庫構建是 Linux 系統編程、模組化架構、插件機制的基石技能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved