Linux gcc编译(动态库,静态库)

1. linux 库路径: /lib , /usr/lib , /usr/local/lib
2.linux 编译静态库

a.编写源文件
vi pr1.c

void print1(){
    printf("static print1() callback ");
}

vi pr2.c
void print2(){
    printf("static print2() callback ");
}

vi main.c
int main(){
    print1();
    print2();
    return 0;
}

b.将库文件编译obj
cc -c pr1.c pr2.c

查看obj 文件
ls -l  pr*.o  

c.链接静态库 , (多个文件打包过程 -r 追加模式)
ar -r libpr.a pr1.o pr2.o

查看打包结果
ar -t libpr.a

d.编译main ,使用静态库 , -L 指定库目录 , -l 指定库文件名 ,源文件 libpr.a 默认需要转换, 去头(lib),去尾(包括.以后部份),为 pr. 多个库,多个文件名,可写多个 -L , -l  , -o 指定编译输出文件名。
gcc -o staticdll main.c -L./ -lpr

e. 运行 ./staticdll

3.编译动态库
a.编写源文件
vi pr1dll.c
void print(){
    printf("this is dll  src ");
}

vi maindll.c
int main(){
    print();
    return 0;
}

b.编绎动态库 -fPIC 指定dll与位置无关 , -o 输出路径 , -shared 指定共享模式
gcc -fPIC -shared -o dll.so pr1dll.c

c.编译主程
gcc -o exedll maindll.c ./dll.so

d.运行: ./exedll




参考资料:
http://www.cnblogs.com/feisky/archive/2010/03/09/1681996.html

原文地址:https://www.cnblogs.com/a_bu/p/4447989.html