linux c 使用第三方库

    xiaoxiao2021-03-25  85

    1.建立max.c文件

    int max(int n1, int n2, int n3) { int max_num = n1; max_num = max_num < n2? n2: max_num; max_num = max_num < n3? n3: max_num; return max_num; } 2.建立max.h文件

    #ifndef __MAX_H__ #define __MAX_H__ int max(int n1, int n2, int n3); #endif 3.建立test.c文件

    #include <stdio.h> #include <max.h> int main(int argc, char *argv[]) { int a = 10, b = -2, c = 100; printf("max among 10, -2 and 100 is %d.\n", max(a, b, c)); return 0; }

    4.将max.c编译成动态库

    gcc -fPIC -shared -o libmax.so max.c

    第一种使用第三方库的方法:

    因为 linux c 标准库文件存放的路径为: /lib 和 /usr/lib

            linux c 标准头文件存放的路径为: /usr/include

    将第三方的库和头文件分别放在以上两个文件夹下,然后进行链接

    gcc test.c -o test -lmax ./test //运行成功

    第一种方法改变了系统标准库的内容,我们是不提倡的,所以我们指定库和头文件的路径即可!

    方法二:

    gcc test.c -o test -I include_path -L lib_path -lyourlib /* include_path 改成你头文件的目录 lib_path 改成你动态库文件的目录 -lyourlib 改成l加上你要引用的库文件名字 比如libmax.so就改成-lmax */ 链接成成功!

    然而当运行的时候会报错:

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

    1.查看程序的库依赖关系.看到libmax.so是找不到了

    $ ldd test

        linux-vdso.so.1 =>  (0x00007ffca89f0000)     libmax.so => not found     libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f8338902000)     /lib64/ld-linux-x86-64.so.2 (0x0000559a98721000)

    原来:Linux是通过 /etc/ld.so.cache 文件搜寻要链接的动态库的。 而 /etc/ld.so.cache 是 ldconfig 程序读取 /etc/ld.so.conf 文件生成的。 (注意, /etc/ld.so.conf 中并不必包含 /lib 和 /usr/lib,ldconfig程序会自动搜索这两个目录)

    如果我们把 libmax.so 所在的路径添加到 /etc/ld.so.conf 中,再以root权限运行ldconfig 程序,更新/etc/ld.so.cache ,test运行时,就可以找到libmax.so。

    1.在/etc/ld.so.conf.d/上新建动态库相应的文件配置文件 这里,我为项目建立了haha.conf 添加上动态库的绝对路径: /home/zyy/test 2.重建/etc/ld.so.cache $sudo ldconfig $ ./test //运行成功!

    但作为一个简单的测试例子,让我们改动系统的东西,似乎不太合适。 还有另一种简单的方法,就是为a.out指定 LD_LIBRARY_PATH。

    LD_LIBRARY_PATH=. ./test

    程序就能正常运行了。LD_LIBRARY_PATH=. 是告诉 test,先在当前路径寻找链接的动态库。

    转载请注明原文地址: https://ju.6miu.com/read-22088.html

    最新回复(0)