如何强制编译 Boost 以使用 -fPIC

how to force compilation of Boost to use -fPIC

本文关键字:-fPIC Boost 何强制 编译      更新时间:2023-10-16

我工作的团队生成了一个用于Python的共享库。 这个库是完全C++的,我们使用 Boost 来公开给 python。 由于我们无法保证客户端安装了 Boost 库,因此我们将 Boost 所需的功能静态引入共享对象文件。 编译的最后阶段对许多人来说看起来很熟悉

g++ -o <output> <objects> -Wl,-Bstatic -lboost_python -lboost_regex ... -Wl,-Bdynamic -shared <other_opts>

我们传统上使用我们自己的 Boost:1.47 版本。 这个版本现在已经很旧了,所以我们希望更新。 然而,奇怪的是,当我在 CentOS 7 系统上使用 yum 安装必要的对象时,我从 gcc 收到以下错误:

relocation R_X86_64_32 against '.rodata.str1.1' can not be used when making a shared object; recompile with -fPIC

好吧,我想我只需下载最新的 boost(CentOS 7 安装了 Boost 1.53)并自行构建。 毕竟,这一直对我们有用。 我按照这里的说明进行操作,但遇到了同样的错误。 如何强制对它构建的静态库使用 -fPIC?

我相信 boost 在编译共享库(.

so 文件)时会自动使用-fPIC,但以下命令在编译静态库(.a 文件)时也使用-fPIC

这对我在 boost 1.46.1 上有用:

sudo ./bjam cxxflags=-fPIC cflags=-fPIC -a ... install

...是添加其他标志(如 threading=multi--layout=tagged)以及要生成的项目列表(例如:--with-regex)的地方。

注意:不需要同时使用 cflagscxxflags,只需要一个。请参阅下面的评论。

参考链接:

  • https://cmake.org/Wiki/TubeTK/Build_Instructions#Boost_.28optional.29
  • http://lists.boost.org/boost-users/2010/07/60682.php

为了方便起见,我结合了之前的回答和评论:

sudo ./bjam cxxflags=-fPIC -a --with-system install
--

with-system 不是必需的,但您可以在其中添加其他 boost 编译选项

它在 CentOS 7 和 boost 1.67 对我有用

另一种解决方案:

./bootstrap.sh
./b2 cxxflags=-fPIC cflags=-fPIC