gpt4 book ai didi

c++ - 如何指定库路径的偏好?

转载 作者:IT老高 更新时间:2023-10-28 12:02:05 26 4
gpt4 key购买 nike

我正在使用 g++ld 编译一个 c++ 程序。我有一个希望在链接期间使用的 .so 库。但是,/usr/local/lib 中存在一个同名的库,并且 ld 正在选择该库而不是我直接指定的库。我该如何解决这个问题?

对于以下示例,我的库文件是 /my/dir/libfoo.so.0。我试过的东西不起作用:

  • 我的 g++ 命令是 g++ -g -Wall -o my_binary -L/my/dir -lfoo bar.cpp
  • /my/dir 添加到我的 $PATH en` 变量的开头或结尾
  • /my/dir/libfoo.so.0 作为参数添加到 g++

最佳答案

将新库所在的路径添加到 LD_LIBRARY_PATH(在 Mac 上名称略有不同...)

您的解决方案应使用 -L/my/dir -lfoo 选项,在运行时使用 LD_LIBRARY_PATH 指向您的库的位置。

Careful with using LD_LIBRARY_PATH - 简而言之(来自链接):

..implications..:
Security: Remember that the directories specified in LD_LIBRARY_PATH get searched before(!) the standard locations? In that way, a nasty person could get your application to load a version of a shared library that contains malicious code! That’s one reason why setuid/setgid executables do neglect that variable!
Performance: The link loader has to search all the directories specified, until it finds the directory where the shared library resides – for ALL shared libraries the application is linked against! This means a lot of system calls to open(), that will fail with “ENOENT (No such file or directory)”! If the path contains many directories, the number of failed calls will increase linearly, and you can tell that from the start-up time of the application. If some (or all) of the directories are in an NFS environment, the start-up time of your applications can really get long – and it can slow down the whole system!
Inconsistency: This is the most common problem. LD_LIBRARY_PATH forces an application to load a shared library it wasn’t linked against, and that is quite likely not compatible with the original version. This can either be very obvious, i.e. the application crashes, or it can lead to wrong results, if the picked up library not quite does what the original version would have done. Especially the latter is sometimes hard to debug.

通过 gcc 使用 rpath 选项到链接器 - 运行时库搜索路径,将被使用而不是查看标准目录(gcc 选项):

-Wl,-rpath,$(DEFAULT_LIB_INSTALL_PATH)

这对于临时解决方案很有用。链接器首先在 LD_LIBRARY_PATH 中搜索库,然后再查看标准目录。

如果您不想永久更新 LD_LIBRARY_PATH,您可以在命令行上即时更新:

LD_LIBRARY_PATH=/some/custom/dir ./fooo

您可以查看链接器知道哪些库使用(示例):

/sbin/ldconfig -p | grep libpthread
libpthread.so.0 (libc6, OS ABI: Linux 2.6.4) => /lib/libpthread.so.0

您可以检查您的应用程序正在使用哪个库:

ldd foo
linux-gate.so.1 => (0xffffe000)
libpthread.so.0 => /lib/libpthread.so.0 (0xb7f9e000)
libxml2.so.2 => /usr/lib/libxml2.so.2 (0xb7e6e000)
librt.so.1 => /lib/librt.so.1 (0xb7e65000)
libm.so.6 => /lib/libm.so.6 (0xb7d5b000)
libc.so.6 => /lib/libc.so.6 (0xb7c2e000)
/lib/ld-linux.so.2 (0xb7fc7000)
libdl.so.2 => /lib/libdl.so.2 (0xb7c2a000)
libz.so.1 => /lib/libz.so.1 (0xb7c18000)

关于c++ - 如何指定库路径的偏好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2726993/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com