动态链接库不是linux独有的特性,在windows下面也存在这样的特性。一般来说,windows下面的动态连接库是以*.dll作为结尾的,而linux下面的动态连接库是以*.so结尾的。和静态链接库相比,动态连接库可以共享内存资源,这样可以减少内存消耗。另外,动态连接是需要经过操作系统加载器的帮助才能被普通执行文件发现的,所以动态连接库可以减少链接的次数。有了这个特点,我们就不难发现为什么很多软件的补丁其实都是以动态库发布的。 那么,在Linux上动态库是怎么生成的呢? [cpp] view plaincopy 1 #include "test.h" 2 3 int add(int a, int b) 4 { 5 return a + b; 6 } 头文件格式, [cpp] view plaincopy 7 #ifndef _TEST_H 8 #define _TEST_H 9 10 int add(int a, int b); 11 #endif 此时如果我们想要生成动态库,要做的工作其实非常简单,输入gcc -shared -fPIC -o libtest.so test.c即可。回车后输入ls,我们就可以发现当前目录下面出现了libtest.so文件。 [cpp] view plaincopy 12 #include <stdio.h> 13 #include "test.h" 14 15 int main() 16 { 17 printf("%d\n", add(2, 3)); 18 return 1; 19 } 在上面的代码当中,我们发现使用到了add函数,那么此时如何才能生成一个执行文件呢?也很简单,输入gcc hello.c -o hello ./libtest.so。然后输入./hello,此时可以验证一下执行文件运行是否正确。在编写静态库的时候,我说过静态库是汇编链接到执行文件当中的,而动态库不会。朋友们可以做个小实验,删除libtest.so,然后输入./hello。此时大家可以看看系统有没有错误返回? [cpp] view plaincopy 20 #ifndef _TEST_H 21 #define _TEST_H 22 23 #ifdef USR_DLL 24 #define DLL_API _declspec(dllexport) 25 #else 26 #define DLL_API _declspec(dllimport) 27 #endif 28 29 DLL_API int add(int a, int b); 30 31 #endif |