我正在尝试将 OpenSSL 静态链接到我的程序中。
链接到可执行文件时效果很好。我需要在共享库(so 或 dll)中使用 OpenSSL,稍后在进程执行时动态加载该库。
尝试将 OpenSSL 静态链接到共享库会导致错误,因为 OpenSSL 未使用 -fPIC 进行编译。是否可以在不重新编译 openssl 的情况下完成此操作?
另外,有没有更好的方法来做到这一点?
最佳答案
I'm trying to static link OpenSSL into my program.
在这种情况下,它很简单:
gcc prog.c /usr/local/lib/libssl.a /usr/local/lib/libcrypto.a -o prog.exe -ldl
It works fine when linking into the executable.
魔鬼代言人...它与位置无关代码 (PIE) 一起工作正常吗?程序上的 PIE 相当于共享对象上的 PIC(无需手动操作)。
gcc -fPIE prog.c /usr/local/lib/libssl.a /usr/local/lib/libcrypto.a -o prog.exe -ldl
根据 GCC 人员的说法,您可以使用 fPIC
进行编译,然后使用 -fPIC
构建一个共享对象或可重定位的可执行文件 -fPIE
。即使用-fPIC
就可以了对于两者。
Trying to statically link OpenSSL into the shared library causes errors due to OpenSSL not being compiled with -fPIC.
这很容易解决。您只需指定 shared
在配置中:
./config shared no-ssl2 no-ssl3 no-comp --openssldir=/usr/local/ssl
make
sudo make install
我认为你也可以(注意缺少 shared
):
export CFLAGS="-fPIC"
./config no-ssl2 no-ssl3 no-comp --openssldir=/usr/local/ssl
make
sudo make install
not being compiled with -fPIC. Is it possible to do this without recompiling openssl?
不,您必须使用 PIC 进行编译以确保 GCC 生成可重定位代码。
Also, is there a better way to do this?
通常你只需配置 shared
。这会触发-fPIC
,这会让您获得可重定位的代码。
您还可以做其他事情,但它们更具侵入性。例如,您可以修改 Configure
行(如 linux-x86_64
),并添加 -fPIC
在第二个字段中。字段之间用冒号分隔,第二个字段是 $cflags
由 OpenSSL 构建系统使用。
可以看修改Configure
的例子在Build OpenSSL with RPATH?
关于c++ - 将 OpenSSL 链接到动态库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30129419/