场景:
main函数需要两个接口,一个求和函数,一个打印函数.
int sum(int i, int j); 求两个int数字的和.
void show(int i, char* name); 打印i的值和它的名称.
现在,需要制作:
一个静态库libcalc.a,提供sum的接口;
一个动态库libshow.so,提供show的接口.
#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.h
#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:
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
[[email protected] libshow]# export LD_LIBRARY_PATH=`pwd`
[[email protected] 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查看依赖的动态库文件
[[email protected] 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)