简体   繁体   English

C程序链接共享库而不设置LD_LIBRARY_PATH

[英]C program linking with shared library without setting LD_LIBRARY_PATH

I was reading Introduction to GCC and it says if a package has both .a and .so. 我正在阅读GCC简介,它说如果一个软件包同时包含.a和.so。 gcc prefer the shared library. gcc更喜欢共享库。 By default the loader searches for shared libraries only in a predefined set of system directories, such as /usr/local/lib and /usr/lib . 默认情况下,加载程序仅在预定义的一组系统目录中搜索共享库,例如/usr/local/lib/usr/lib If the library is not located in one of these directories it must be added to the load path, or you need to use -static option to force it to use the .a library. 如果库不在其中一个目录中,则必须将其添加到加载路径,或者您需要使用-static选项强制它使用.a库。 However, I tried the following: 但是,我尝试了以下方法:

vim hello.c: vim hello.c:

#include <gmp.h>
#include <stdio.h>

int main() {
        mpz_t x;
        mpz_init(x);
        return 0;
}

gcc hello.c -I/opt/include -L/opt/lib -lgmp  (my gmp library is in opt)
./a.out

And it runs. 它运行。 The book says it should have the following error: 该书说它应该有以下错误:

./a.out: error while loading shared libraries:
libgdbm.so.3: cannot open shared object file:
No such file or directory

(well, the book uses GDBM as example but I used GMP, but this won't matter right?) (好吧,这本书以GDBM为例,但我使用的是GMP,但这没关系吗?)

However, I did not set LD_LIBRARY_PATH=/opt/lib , and as you can see I did not use -static option either, but a.out still runs. 但是,我没有设置LD_LIBRARY_PATH=/opt/lib ,你可以看到我也没有使用-static选项,但a.out仍然运行。

Can you all tell me why and show me how to get the error described in the book? 你能告诉我为什么,并告诉我如何得到书中描述的错误? Yes I want the error so I will understand what I misunderstood. 是的我想要错误,所以我会理解我误解的内容。

From your response to my comment: 从您对我的评论的回复:

linux-gate.so.1 => (0xb7746000)
libgmp.so.10 => /usr/lib/i386-linux-gnu/libgmp.so.10 (0xb76c5000)
libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0xb7520000)
/lib/ld-linux.so.2 (0xb7747000) 

So, your program is picking up the lib from /usr/lib . 所以,你的程序正在从/usr/lib

What you can try to do is rename the lib in your /opt/lib , and link against the new name. 您可以尝试做的是重命名/opt/lib ,并链接新名称。

mv /opt/lib/libgmp.so /opt/lib/libgmp-test.so
gcc hello.c -I/opt/include -L/opt/lib -lgmp-test

Then try running the program. 然后尝试运行该程序。 Also, compare the result of ldd against the new a.out against what you got before. 另外,将ldd与新a.out的结果与之前的结果进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM