如何link自己编译的zlib共享库?

How to link my own compiled zlib share library?

我编译了一个链接自己编译的zlib动态库的程序,结果链接的是系统的zlib动态库

我是这样编译的:

root@dggphisprd24174:/test_zlib/myprog# uname -a
Linux dggphisprd24174 4.15.0-163-generic #171-Ubuntu SMP Fri Nov 5 11:55:11 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux
root@dggphisprd24174:/test_zlib# echo $LIBRARY_PATH

root@dggphisprd24174:/test_zlib# ls
myprog  zlib
root@dggphisprd24174:/test_zlib# cd zlib && ./configure > /dev/null && make > /dev/null && cd ../myprog
root@dggphisprd24174:/test_zlib/myprog# ls
main.c
root@dggphisprd24174:/test_zlib/myprog# gcc -I../zlib -o prog main.c -lz -L../zlib
root@dggphisprd24174:/test_zlib/myprog# ls
main.c  prog
root@dggphisprd24174:/test_zlib/myprog# ldd prog
        linux-vdso.so.1 (0x00007ffd3190e000)
        libachk.so => /lib/libachk.so (0x00007ff936fa5000)
        libz.so.1 => /lib/x86_64-linux-gnu/libz.so.1 (0x00007ff936a71000)
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007ff936680000)
        libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007ff93647c000)
        libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007ff93625d000)
        librt.so.1 => /lib/x86_64-linux-gnu/librt.so.1 (0x00007ff936055000)
        /lib64/ld-linux-x86-64.so.2 (0x00007ff936e90000)

ldd 编排显示:libz.so.1 => /lib/x86_64-linux-gnu/libz.so.1.

分享库不是自己编译的

看得我一头雾水


main.c 文件的内容

#include <stdlib.h>
#include "zlib.h"

// test link libz.so
int main()
{
        char* in = "hello,hello";
        char* out = calloc(30, 1);

        z_stream strm;
        strm.zalloc = 0;
        strm.zfree = 0;
        strm.next_in = in;
        strm.avail_in = 11;
        strm.next_out = out;
        strm.avail_out = 30;

        deflateInit(&strm, 1);
        deflate(&strm, Z_FINISH);
        deflateEnd(&strm);
}

尝试LD_LIBRARY_PATH=../zlib ./examplesh

您可以在构建 examplesh 时添加 -Wl,-rpath,../zlib