gcc编译静态库和动态库

来源:互联网 发布:java独立开发 编辑:程序博客网 时间:2024/04/18 22:19
1.静态库的编译与使用
[wang@localhost 桌面]$ vim test.c
#include <stdio.h>
int display()
{
printf("we are the best!\n");
return 0;
}

[wang@localhost 桌面]$ gcc -c test.c
[wang@localhost 桌面]$ ar crv libtest.a test.o 
a - test.o
[wang@localhost 桌面]$ ranlib libtest.a 
[wang@localhost 桌面]$ vim tt.c
#include <stdio.h>
int main()
{
display();
return 0;
}

[wang@localhost 桌面]$ gcc -o tt.x tt.c -L. -ltest
[wang@localhost 桌面]$ ./tt.x 
we are the best!

2.动态库的编译和使用
[wang@localhost 桌面]$ gcc test.c -fPIC -shared -o libtest.so
–fPIC:表示编译为位置独立的代码,不用此选项的话,编译后的代码是位置相关的。所以动态载入时是通过代码拷贝的方式来满足不同进程的需要,而不能达到真正代码段共享的目的。
–shared:指明编译成动态库

[wang@localhost 桌面]$ gcc tt.c -L. -l test -o tt
[wang@localhost 桌面]$ ./tt
./tt: error while loading shared libraries: libtest.so: cannot open shared object file: No such file or directory
[wang@localhost 桌面]$ gcc -o tt tt.c ./libtest.so
[wang@localhost 桌面]$ ./tt
we are the best!


原创粉丝点击