1,编译,使用shared和- fpic生成动态链接库
库源码:test.c
<代码> # include & lt; stdio.h> # include & lt; string.h> # include & lt; stdlib.h> 静态孔隙printline (int len) { int我; (i=0; i< len;我+ +) { printf ("="); } printf (" \ n "); } 空白打印(char * s) { int len=0; int i=0; 如果(!年代| | * s==' \ 0 ') { 返回; } len=strlen (s); printline (len); printf (" % s \ n ", s); printline (len); }代码>
头文件:test.h
<代码>的ifndef __TEST_H__ #定义__TEST_H__ 空白打印(char *); # endif 代码>
编译库文件:
<代码> gcc测试。c - shared - fpic - o libtest.so 代码>
2。编译测试代码
测试代码:c
<代码> # include“test.h” int main () { char teststr []=癶ello world”; 打印(teststr); 返回0; }代码>
编译测试代码
<代码>主要gcc。c - l。主要/-ltest - o 代码>
3。运行
当运行时,发现找不到库文件
。/主要:当加载共享库时发生错误:libtest。所以:不能打开共享对象文件:没有这样的文件或目录
这个是linux库文件搜索路径的问题,有两个解决方式
-
<李>在/etc/ld.so.conf.d/下编写配置文件,指定库路径,然后使用ldconfig去刷新缓存李>
<李>在执行前设置环境变量LD_LIBRARY_PATH,指定当前的路径,再去执行时,则现在本地去搜索李>
<代码> root@GFD: ~/workspace/so_test #出口LD_LIBRARY_PATH=?root@GFD: ~/workspace/so_test #。/主要===========你好,世界===========代码>