場景:linux
main函數須要兩個接口,一個求和函數,一個打印函數.函數
int sum(int i, int j); 求兩個int數字的和.測試
void show(int i, char* name); 打印i的值和它的名稱.spa
如今,須要製做:.net
一個靜態庫libcalc.a,提供sum的接口; code
一個動態庫libshow.so,提供show的接口.blog
#include <stdio.h> #include "calc.h" #include "show.h" int main(void) { int s; int i = 1; int j = 2; s = sum(i,j); show(i,"i"); show(j,"j"); show(s,"sum"); }
calc.c, calc.h接口
#include "calc.h" int sum(int i, int j) { return(i+j); } ~
#ifndef __CALC_H__ #define __CALC_H__ int sum(int i, int j); #endif
show.c, show.hget
#include "show.h" void show(int i, char* name) { printf("%s=%d\n", name, i); } ~
#ifndef __SHOW_H__ #define __SHOW_H__ void show(int i, char* name); #endif ~
Makefile:it
CC = gcc all: main main: libcalc.a main.c libshow.so gcc -o main main.c -L. -lcalc -lshow
lib: libcalc.a libshow.so libcalc.a : calc.o ar crs libcalc.a calc.o calc.o : calc.c $(CC) -c calc.c -o calc.o libshow.so: show.o $(CC) -shared -o libshow.so show.o show.o: show.c $(CC) -fPIC -Wall -c show.c -o show.o
clean: rm -rf *.o *.so *.a main
輸入: make all --- 生成libcalc.a,libshow.so庫和main可執行程序
make lib --- 生成libcalc.a,libshow.so庫
make clean --- 清除目標文件
輸入: export LD_LIBRARY_PATH=`pwd` --- 添加當前路徑到動態庫路徑環境變量LD_LIBRARY_PATH
[root@localhost libshow]# export LD_LIBRARY_PATH=`pwd`
[root@localhost libshow]# echo $LD_LIBRARY_PATH
/work/jz2440/test/libshow\
輸入: ./main 測試結果.
i=1
j=2
sum=3
=====================
關於動態庫和靜態庫的相關知識:
1. linux編譯動態庫和靜態庫的makefile示例 http://blog.csdn.net/shaoxiaohu1/article/details/46943417
2. 三種方法使得裝載器正確尋找並加載到動態庫:
a. 將libx.so移到系統庫文件目錄下
b. export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:`pwd`
c. 使用配置文件告訴系統動態庫的路徑.
vi /etc/ld.so.conf.d/xxxx.conf
/work/jz2440/test/libshow
3. ldd xxxx查看依賴的動態庫文件
[root@localhost libshow]# ldd main
linux-vdso.so.1 => (0x00007fff1edc0000)
libshow.so => /work/jz2440/test/libshow/libshow.so (0x00002ad8d3511000) libc.so.6 => /lib64/libc.so.6 (0x0000003a4fc00000) /lib64/ld-linux-x86-64.so.2 (0x0000003a4f800000)