天天看点

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

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

[[email protected] main5]#gcc -c helloDog.c helloCat.c      //将hello1.c和hello2.c分别编译为helloDog.o和helloCat.o,其中-c选项意为只编译不链接。 [[email protected] main5]#ar -r libhello.a helloDog.o helloCat.o    //将hello1.o和hello2.o组合为libhello.a

(一定要以lib开头)

这个静态链接库 [[email protected] main5]#cp libhello.a /usr/lib      //将libhello.a拷贝到/usr/lib目录下,作为一个系统共享的静态链接库 [[email protected] main5]#gcc -o main main.c -lhello   //将main.c编译为可执行程序main,这个过程用到了-lhello  (这个hello要跟libhello.a的红色部分对应)选项,这个选项告诉gcc编译器到/usr/lib目录下去找

libhello.a(一定要以lib开头)

的静态链接库 [[email protected] main5]#./main helloDog helloCat

方法二:将helloDog.o和helloCat.o组合成动态链接库.so

[[email protected] main5]#gcc -c -fpic helloDog.c helloCat.c     //将helloDog.c和helloCat.c编译成helloDog.o和helloCat.o,-c意为只编译不链接,-fpic意为位置独立代码,指示编译程序生成的代码要适合共享库的内容这样的代码能够根据载入内存的位置计算内部地址。 [[email protected] main5]#gcc -shared helloDog.o helloCat.o -o hello.so    //将helloDog.o和helloCat.o组合为shared object,即动态链接库 [[email protected] main5]#cp hello.so /usr/lib     //将hello.so拷贝到/usr/lib目录下 [[email protected] main5]#gcc -o hello hello.c /usr/lib/hello.so(貌似要用绝对路径,) //将hello.c编译链接为hello的可执行程序,这个过程用到了动态链接库hello.so [[email protected] main5]#./main helloDog helloCat

c++

继续阅读