本練習採用下面四個C文件, addvec.c multvec.c 和 vector.h 是庫文件, main2.c是引用庫函數的文件
/* vector.h */
/* prototypes for libvector */
void addvec(int *x, int *y, int *z, int n);
void multvec(int *x, int *y, int *z, int n);
int getcount();
/* addvec.c */
int addcnt = 0;
void addvec(int *x, int *y, int *z, int n)
{
int i;
addcnt++;
for (i = 0; i < n; i++)
z[i] = x[i] + y[i];
}
/* multvec.c */
int multcnt = 0;
void multvec(int *x, int *y, int *z, int n)
{
int i;
multcnt++;
for (i = 0; i < n; i++)
z[i] = x[i] * y[i];
}
/* main2.c */
#include <stdio.h>
#include "vector.h"
int x[2] = {1, 2};
int y[2] = {3, 4};
int z[2];
int main()
{
addvec(x, y, z, 2);
printf("z = [%d %d]\n", z[0], z[1]);
return 0;
}
靜態鏈接庫的構建
編譯庫文件,並打包成靜態庫
# create a static library libvector.a
gcc -c addvec.c multvec.c
ar rcs libvector.a addvec.o multvec.o
構建引用靜態庫的可執行文件
# build the executable
gcc -c main2.c
gcc -o prog2c main2.o ./libvector.a
# or equivalently
gcc -o prog2c main2.o -L. -lvector
運行成功
$ ./prog2c
z = [4 6]
如果鏈接的過程加 -static
選項表示針對系統庫引用也以靜態庫的方式引入,如下所示:
gcc -static -o prog2c main2.o -L. -lvector
下面刪除./libvector.a, 然後測試一下動態鏈接庫的構建過程。
動態鏈接庫的構建
編譯庫文件,並打包成動態鏈接庫
# build a shared library libvector.so
# The -fpic flag directs the compiler to generate position-independent code. The -shared flag directs the linker to create a shared object file.
gcc -shared -fpic -o libvector.so addvec.c multvec.c
構建引用動態庫的可執行文件
# Once we have created the library, we would then link it into our example program
gcc -o prog2l main2.c ./libvector.so
運行成功
$ ./prog2l
z = [4 6]
但是假如我用下面的方式構建引用動態庫的可執行文件,會發生什麼呢?
gcc -o prog2l main2.o -L. -lvector
運行,發現報錯了
$ ./prog2l
./prog2l: error while loading shared libraries: libvector.so: cannot open shared object file: No such file or directory
原來是需要在 /etc/ld.so.conf
文件中設置動態鏈接庫的尋找路徑。
把動態鏈接庫所在路徑配置進去後,再執行一下 sudo ldconfig
命令。
重新編譯
gcc -o prog2l main2.o -lvector
運行
$ ./prog2l
z = [4 6]