我有以下问题:
我正在尝试使用默认的 gnu 编译器 (gcc-7) 和可用的链接器版本在 Ubuntu18 上构建软件。
现在我们遇到这样的情况,一个可执行文件可以链接一个共享库,该共享库又链接另一个共享库。因此,可执行文件具有次要依赖性。但次要依赖项仅从 rpath 中获取,而不是从 runpath 中获取。因此,即使辅助依赖项放置在可执行文件的运行路径文件夹中,也不会找到它。
结合使用 googletest 和 cmake 时发现了该问题。由于未找到次要依赖项,因此无法编译测试。所以设置LD_LIBRARY_PATH
可能不是一个选择,或者至少使一切变得更加复杂。
以下是 Ubuntu 18 系统上 gcc-7 出现问题的示例(但在 Ubuntu 16 上使用 gcc-5 工作正常):
二级.hpp
#include <string>
class World{
public:
std::string world();
};
次要.cpp
#include "secondary.hpp"
std::string World::world(){
return "world";
}
初级.hpp
#include <string>
class Hello{
public:
std::string helloWorld();
};
主要.cpp
#include "primary.hpp"
#include "secondary.hpp"
#include <sstream>
std::string Hello::helloWorld(){
std::stringstream strm;
World world;
strm << "hello ";
strm << world.world();
strm << "!";
return strm.str();
}
并像这样编译两个库
mkdir build
cd build
gcc -shared -o libsecondary.so -fPIC ../secondary.cpp
gcc -shared -o libprimary.so -fPIC ../primary.cpp -lsecondary -L$(pwd)
如果我现在从以下文件构建一个可执行文件
main.cpp
#include "primary.hpp"
#include <iostream>
int main(int argc, char** argv){
Hello hello;
std::cout << hello.helloWorld() << std::endl;
}
通过在新的构建目录中执行以下操作(与前一个目录平行)
cd ..
mkdir build_app
cd build_app
gcc -o app ../main.cpp -L../build -lstdc++ -lsecondary -lprimary -Wl,-rpath=$(pwd)/../build
如果我现在这样做ldd app
我看到libsecondary.so
没有找到
linux-vdso.so.1 (0x00007fff0cf8c000)
libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f9e86fe7000)
libprimary.so => <some_path>/libprimary.so (0x00007f9e86de5000)
libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f9e86bcd000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f9e867dc000)
libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f9e8643e000)
/lib64/ld-linux-x86-64.so.2 (0x00007f9e87573000)
libsecondary.so => not found
应用程序的运行路径是(通过运行readelf -d app
)
Dynamic section at offset 0x1d40 contains 31 entries:
Tag Type Name/Value
0x0000000000000001 (NEEDED) Shared library: [libstdc++.so.6]
0x0000000000000001 (NEEDED) Shared library: [libprimary.so]
0x0000000000000001 (NEEDED) Shared library: [libgcc_s.so.1]
0x0000000000000001 (NEEDED) Shared library: [libc.so.6]
0x000000000000001d (RUNPATH) Library runpath:[<some_path>/build]
问题是,为什么ld
没有服用libsecondary.so
从运行路径app
? Both libprimary.so
and libsecondary.so
放在同一个文件夹中,但仅libprimary.so
被发现。
该问题的一种解决方案是编译--disable-new-dtags
它将使用 rpath 而不是 runpath,并且是 Ubuntu16 上 gcc-5 的默认设置。然而,ld 似乎已弃用 rpath 的使用。
那么将 runpath 与辅助依赖项一起使用的正确方法是什么?