g ++:如何指定库路径的首选项? [英] g++: how to specify preference of library path?
问题描述
我正在使用 g ++
和 ld
编译一个c ++程序。我有一个 .so
库我想在链接过程中使用。但是,在 / usr / local / lib
中存在同名的库,而 ld
我直接指定的。
I'm compiling a c++ program using g++
and ld
. I have a .so
library I want to be used during linking. However, a library of the same name exists in /usr/local/lib
, and ld
is choosing that library over the one I'm directly specifying. How can I fix this?
对于下面的示例,我的库文件为 /my/dir/libfoo.so.0
。我尝试过的东西不起作用:
For the examples below, my library file is /my/dir/libfoo.so.0
. Things I've tried that don't work:
- 我的g ++命令是
g ++ -g -Wall -o my_binary -L / my / dir -lfoo bar.cpp
- 添加
/ my / dir
$ PATH
en`变量 - 添加
/my/dir/libfoo.so的开头或结尾。 0
作为g ++的参数
- my g++ command is
g++ -g -Wall -o my_binary -L/my/dir -lfoo bar.cpp
- adding
/my/dir
to the beginning or end of my$PATH
en` variable - adding
/my/dir/libfoo.so.0
as an argument to g++
推荐答案
LD_LIBRARY_PATH
(在Mac上有稍微不同的名称)的路径
Add the path to where your new library is to LD_LIBRARY_PATH
(it has slightly different name on Mac ...)
您的解决方案应该使用 -L / my / dir -lfoo
选项,在运行时使用LD_LIBRARY_PATH指向库的位置。
Your solution should work with using the -L/my/dir -lfoo
options, at runtime use LD_LIBRARY_PATH to point to the location of your library.
OR
使用rpath选项通过gcc到链接器 - 运行时库搜索路径,将使用
(gcc选项):
Use the rpath option via gcc to linker - runtime library search path, will be used instead of looking in standard dir (gcc option):
-Wl,-rpath,$(DEFAULT_LIB_INSTALL_PATH)
这对于临时解决方案很有用。链接器在查找标准目录之前首先搜索库的LD_LIBRARY_PATH。
This is good for a temporary solution. Linker first searches the LD_LIBRARY_PATH for libraries before looking into standard directories.
如果不想永久更新LD_LIBRARY_PATH,可以在命令行中执行: / p>
If you don't want to permanently update LD_LIBRARY_PATH you can do it on the fly on command line:
LD_LIBRARY_PATH=/some/custom/dir ./fooo
您可以检查链接器知道使用哪些库(示例):
You can check what libraries linker knows about using (example):
/sbin/ldconfig -p | grep libpthread
libpthread.so.0 (libc6, OS ABI: Linux 2.6.4) => /lib/libpthread.so.0
您可以检查您的应用程序正在使用哪个库: p>
And you can check which library your application is using:
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)
这篇关于g ++:如何指定库路径的首选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!