您的位置:首页 > 编程语言 > C语言/C++

c++ 编译静态库,动态库

2015-01-11 10:08 281 查看
hello1.c ————————————————————#include <stdio.h>
void printDog() {  printf("hello dog");    }

_________________________________________________hello2.c #include <stdio.h>
void printCat() { printf("hello cat"); }____________________________________________________main.c void print1(int); void print2(char *);
int main() { helloDog();helloCat(); }
可以看到main.c要用到helloDog.c中的print1函数和hello2.c中的print2函数。所以可以把这两个函数组合为库,以供更多的程序作为组件来调用。
方法一:将hello1.c和hello2.c编译成静态链接库.a[root@localhost main5]#gcc -c helloDog.c helloCat.c     //将hello1.c和hello2.c分别编译为helloDog.o和helloCat.o,其中-c选项意为只编译不链接。[root@localhost main5]#ar -r libhello.a helloDog.o helloCat.o   //将hello1.o和hello2.o组合为libhello.a(一定要以lib开头)[/b]这个静态链接库[root@localhost main5]#cp libhello.a /usr/lib     //将libhello.a拷贝到/usr/lib目录下,作为一个系统共享的静态链接库[root@localhost main5]#gcc -o main main.c -lhello  //将main.c编译为可执行程序main,这个过程用到了-lhello  (这个hello要跟libhello.a的红色部分对应)选项,这个选项告诉gcc编译器到/usr/lib目录下去找libhello.a(一定要以lib开头)的静态链接库[root@localhost main5]#./mainhelloDoghelloCat
方法二:将helloDog.o和helloCat.o组合成动态链接库.so[root@localhost main5]#gcc -c -fpic helloDog.c helloCat.c    //将helloDog.c和helloCat.c编译成helloDog.o和helloCat.o,-c意为只编译不链接,-fpic意为位置独立代码,指示编译程序生成的代码要适合共享库的内容这样的代码能够根据载入内存的位置计算内部地址。[root@localhost main5]#gcc -shared helloDog.o helloCat.o -o hello.so   //将helloDog.o和helloCat.o组合为shared object,即动态链接库[root@localhost main5]#cp hello.so /usr/lib    //将hello.so拷贝到/usr/lib目录下[root@localhost main5]#gcc -o hello hello.c /usr/lib/hello.so(貌似要用绝对路径,)//将hello.c编译链接为hello的可执行程序,这个过程用到了动态链接库hello.so[root@localhost main5]#./mainhelloDoghelloCat
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: