链接器抱怨缺少 -fPIC

Linker complains about missing -fPIC

我正在尝试交叉编译冻结的 Cython 程序以在 RPi 上使用。

Link 产生(对于 Python 库的许多对象)

/usr/bin/arm-linux-gnueabihf-ld: 
/root/xxx_Build/usr/local/lib/python3.7/config-3.7m-arm-linux-gnueabihf/libpython3.7m.a(getopt.o): relocation R_ARM_THM_MOVW_ABS_NC against `a local symbol' can not be used when making a shared object; recompile with -fPIC

链接器应该创建可执行文件(而不是共享对象)。为什么?

编译(我的模块):

cython_freeze.py -o main.c sub.py
cython sub2.py

{crossPrefix}gcc -fPIC -pthread -O2 -Wall -Wextra -fno-strict-aliasing -fwrapv -I{crossRoot}{pythonInclude} -c -o main.o main.c'
{crossPrefix}gcc -fPIC -pthread -O2 -Wall -Wextra -fno-strict-aliasing -fwrapv -I{crossRoot}{pythonInclude} -c -o sub.o sub.c'

Link:

{crossPrefix}gcc -Xlinker -export-dynamic -L{crossRoot}/usr/local/lib/{pythonCommand}/config-{pythonVersion}m-{crossPrefixM} main.o sub.o -l{pythonCommand}m -lm -lpthread -ldl -lutil -o 

版本:

以上过程适用于

The linker should create an executable (and not a shared object). Why?

从 Ubuntu 17.04 开始,Ubuntu 加入了 GCC 构建配置的趋势 默认情况下生成 PIE(位置独立可执行文件),因此生成 PIC 对象 默认情况下的文件。 PIE 加强了系统安全性,因为这样的可执行文件可以 运行 在 ASLR

存在的情况下

参见:

$ cat /etc/*-release | grep VERSION
VERSION="18.04.1 LTS (Bionic Beaver)"
VERSION_ID="18.04"
VERSION_CODENAME=bionic

$ echo "int main(void) { return 0; }" | gcc -x c -
$ file a.out
a.out: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=3597d2a178dfb7ff7b0ba10886819bf19e40d596, not stripped

PIE 个共享对象,因此必须编译PIE 链接中的所有目标文件-fPIC。这会 默认情况下新编译的目标文件是真的,但显然不是你的目标文件 libpython3.7m.a.

您可以通过在链接选项中添加 -no-pie 来坚持使用老式的可执行文件。 (在这种情况下,您不需要使用 -fPIC 编译您自己的代码)。