g++ 编译:我可以 link 到带有 symlinked 二进制文件的目录吗?
g++ compiling: can I link to a directory with symlinked binaries?
编译如下:
g++ -L../../lib -o my_prog my_prog.cpp -ltest1 -ltest2
其中 ../../lib
包含指向 libtest1.so 和 libtest2.so
的符号链接
但是当我 运行 程序时出现错误:"error while loading shared libraries: libtest1.so: cannot open shared object file: No such file or directory" 我不确定符号链接是否是罪魁祸首。
运行时发生的事情与rpath有关。
您可能希望(不推荐,参见 this)在 运行 可执行文件之前适当地设置您的 LD_LIBRARY_PATH
,或者更好的是您希望在 linking 它(例如,通过将 -Wl,--rpath $(realpath ../../lib/)
传递给 g++
命令执行 link.
阅读 Drepper 的 How to write shared libraries paper and the Program Library HowTo
选项 -L
供链接器 ld
在链接期间查找 .a
和 .so
。
选项 -Wl,-rpath=
用于 动态链接器 ld.so 在应用程序为 运行 时查找 .so
。当所需的共享库不在 /etc/ld.so.conf
.
中指定的(标准系统)目录中时,您需要使用 -Wl,-rpath=
使用 $ORIGIN
动态链接器 变量使 rpath 相对于您的可执行文件的路径:
g++ -L../../lib -Wl,-rpath='${ORIGIN}/../../lib' -o my_prog my_prog.cpp -ltest1 -ltest2
小心确保 ${ORIGIN}
不是 由 shell 或您的 makefile 扩展(这就是它在单引号中的原因)。
$ORIGIN
and rpath
ld.so
understands the string $ORIGIN
(or equivalently ${ORIGIN}
) in an rpath specification (DT_RPATH
or DT_RUNPATH
) to mean the directory containing the application executable. Thus, an application located in somedir/app could be compiled with gcc -Wl,-rpath,'$ORIGIN/../lib'
so that it finds an associated shared library in somedir/lib no matter where somedir is located in the directory hierarchy. This facilitates the creation of "turn-key" applications that do not need to be installed into special directories, but can instead be unpacked into any directory and still find their own shared libraries.
编译如下:
g++ -L../../lib -o my_prog my_prog.cpp -ltest1 -ltest2
其中 ../../lib
包含指向 libtest1.so 和 libtest2.so
但是当我 运行 程序时出现错误:"error while loading shared libraries: libtest1.so: cannot open shared object file: No such file or directory" 我不确定符号链接是否是罪魁祸首。
运行时发生的事情与rpath有关。
您可能希望(不推荐,参见 this)在 运行 可执行文件之前适当地设置您的 LD_LIBRARY_PATH
,或者更好的是您希望在 linking 它(例如,通过将 -Wl,--rpath $(realpath ../../lib/)
传递给 g++
命令执行 link.
阅读 Drepper 的 How to write shared libraries paper and the Program Library HowTo
选项 -L
供链接器 ld
在链接期间查找 .a
和 .so
。
选项 -Wl,-rpath=
用于 动态链接器 ld.so 在应用程序为 运行 时查找 .so
。当所需的共享库不在 /etc/ld.so.conf
.
-Wl,-rpath=
使用 $ORIGIN
动态链接器 变量使 rpath 相对于您的可执行文件的路径:
g++ -L../../lib -Wl,-rpath='${ORIGIN}/../../lib' -o my_prog my_prog.cpp -ltest1 -ltest2
小心确保 ${ORIGIN}
不是 由 shell 或您的 makefile 扩展(这就是它在单引号中的原因)。
$ORIGIN
and rpath
ld.so
understands the string$ORIGIN
(or equivalently${ORIGIN}
) in an rpath specification (DT_RPATH
orDT_RUNPATH
) to mean the directory containing the application executable. Thus, an application located in somedir/app could be compiled withgcc -Wl,-rpath,'$ORIGIN/../lib'
so that it finds an associated shared library in somedir/lib no matter where somedir is located in the directory hierarchy. This facilitates the creation of "turn-key" applications that do not need to be installed into special directories, but can instead be unpacked into any directory and still find their own shared libraries.