Linux中静态库与动态库的制作
库的命名规则
静态库:libxxx.a
动态库:libxxx.so
1.创建静态库
头文件la.h
#ifndef _LA_H_
#define _LA_H_
#include <stdio.h>
void testfun(void *str);
#endif
源文件la.c
#include "la.h"
void testfun(char *str)
{
puts("str");
}
编译:#gcc -c la.c -o la.o ------>la.o
#ar arc libmyla.a la.o ------>libmyla.a
主函数main.c
#include "la.h"
int main()
{
char str[]="helloworkd";
testfun(str);
}
编译:gcc main.c -o main -L. -lmyla ---->在当前文件下链接静态库文件
2.创建动态库:
头文件la.h
#ifndef _LA_H_
#define _LA_H_
#include <stdio.h>
void testfun(void *str);
#endif
源文件la.c
#include "la.h"
void testfun(char *str)
{
puts("str");
}
编译:#gcc -fPIC -Wall -c la.c -o la.o ---->la.o
#gcc -shared -o libmyla.so la.o ---->libmyla.so
主函数main.c
#include "la.h"
int main()
{
char str[]="helloworkd";
testfun(str);
}
三种方法加载:
<一>修改运行环境:---->目的是告诉动态加载器应该加载那个共享库
打开 /etc/ld.so.conf.d
新建一个mylib.conf 加入/program/test/ 这个就是libmyla.so所在的路径
刷新一下:ldconfig
编译:gcc main.c -L. -lmyla -o main //-L.表示加载当前文件夹得库
<二>修改运行环境:export LD_LIBRARY_PATH=/program/test/ 对当前有效
编译:gcc main.c -L. -lmyla -o main
<三>拷贝libmyla.so 到/lib下面 系统默认的库文件中
编译:gcc main.c -lmyla -o main
尊重作者,请转明来处:追Dream梦http://blog.csdn.net/pzhsunxu/article/details/7798301