Skip to content
Rain Hu's Workspace
Go back

[IT] 動態鏈結庫(DDL)

Rain Hu

動態鏈結庫(Dynamic Linked Library, DDL)

示例

// math.c
int add(int a, int b)
{
    return a + b;
}
// math.h
int add(int a, int b);
$ gcc -shared -fPIC math.c -o libmath.so
// main.c
#include <stdio.h>
#include <math.h>

int main()
{
    printf("add(1, 2) returns %d\n", add(1, 2));
    return 0;
}
gcc main.c -lmath -L. -o main

系統在路徑下找不到文件的解決方案

  1. 將動態庫複製到系統路徑下(需要 root 權限)
$ sudo ^C cp libmath.so /usr/local/lib/
  1. 使用環境變量,將當前目錄加到 LD_LIBRARY_PATH 環境變量中
$ export LD_LIBRARY_PATH="$(pwd)"       // 將當前目錄叫到 LD_LIBRARY_PATH中
$ echo $LD_LIBRARY_PATH                 // 測試是否調用成功

Share this post on:

Previous
[DS] 演算法筆記
Next
[IT] MySQL Functions