您的位置:首页 > 其它

动态库、静态库初试

2016-10-09 11:44 134 查看
//main.c
1 #include
2 #include
3 void hello(char *str)
4 {
5 printf("hello world!%s\n",str);
6 }
//hello.h
3 void hello(char *str);
//hello.c
1 #include
2 #include
3 void hello(char *str)
4 {
5 printf("hello world!%s\n",str);
6 }

静态库实在程序编译阶段已经连接到目标代码中,在实际程序运行的时候不需要再次使用该静态库;

动态库(共享库):编译阶段不需要连接,只要包含头文件包含所需要的函数、变量声明即可,在程序运行阶段载入动态库;

   举例;三个文件---main.c;hello.c;hello.h,

//main.c
1 #include<stdio.h>
2 #include<string.h>
3 void hello(char *str)
4 {
5 printf("hello world!%s\n",str);
6 }
//hello.h
3 void hello(char *str);
//hello.c
1 #include<stdio.h>
2 #include<string.h>
3 void hello(char *str)
4 {
5 printf("hello world!%s\n",str);
6 }
1.1——生成.o文件

     gcc -c hello.c       静态库和动态库都需要通过此文件生成。

1.2——生成静态库,前缀为lib,后缀.a

    ar cr  libhello.a hello.o       ls一下可以看到生成了libhello.a文件

1.3——使用静态库

    gcc -o main main.c -L. -lhello    生成可执行文件main    ,删除静态库,运行可执行文件运行正常

2.1——系统不同,需要重新生成.o文件

   gcc -c -fpic  hello.c

2.2——生成动态库

     gcc -shared -fpic  -o libhello.so heiio.o        生成动态库文件

2.3——使用动态库

     gcc -o  main man,c -L. -lhello  可以生成可执行文件,运行会出现错误:

          ./main: error while loading shared libraries: libhello.so: cannot open shared object file: No such file or directory

 
  cp libhello.so /lib,运行./main 结果正常 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: