Distutils 在构建 python 扩展时部分忽略 CC 环境变量

R_B*_*rie 2 python gcc distutils setuptools

我正在尝试安装 subprocess32 python 模块(https://github.com/google/python-subprocess32),但 distutils 遇到一些问题。该模块包含必须构建的 C 扩展,但是当我运行 或 时,pip install .python setup.py install得到以下输出:

...
creating build
creating build/temp.linux-x86_64-2.7
/non/existent/path/gcc -pthread -fPIC ... -c _posixsubprocess.c -o build/temp.linux-x86_64-2.7/_posixsubprocess.o
unable to execute '/non/existent/path/gcc': No such file or directory
Run Code Online (Sandbox Code Playgroud)

显然,由于某种原因,distutils 使用了错误的 gcc 路径。然后我尝试使用手动指定 gcc 的正确路径export CC=/correct/path/to/gcc,得到以下输出:

building '_posixsubprocess' extension
creating build/temp.linux-x86_64-2.7
/correct/path/to/gcc -fPIC -fno-strict-aliasing -g -O2 ... -c _posixsubprocess.c -o build/temp.linux-x86_64-2.7/_posixsubprocess.o
/non/existent/path/gcc -pthread -shared ... build/temp.linux-x86_64-2.7/_posixsubprocess.o -o build/lib.linux-x86_64-2.7/_posixsubprocess.so
unable to execute '/non/existent/path/gcc': No such file or directory
Run Code Online (Sandbox Code Playgroud)

原来有问题的命令现在使用了正确的路径,但它仍然尝试使用 gcc 的错误位置来构建共享库。我是否需要指定另一个环境变量来纠正此行为?

onl*_*ice 5

我和你实验过完全相同的问题。我花了一些时间挖掘distutils源代码并发现了问题。

distutils将使用 Python 构建时的链接配置。在这种情况下,用于构建 python 的 gcc 与用于构建扩展的 gcc 不同。

运行此命令也可查看默认链接命令:

python2 "from distutils.sysconfig import get_config_var; print(get_config_var('LDSHARED'))"
Run Code Online (Sandbox Code Playgroud)

您应该发现不正确的 gcc 位于配置的开头,例如:

/non/existent/path/gcc -pthread -shared
Run Code Online (Sandbox Code Playgroud)

第一个解决方案

设置LDSHARED环境变量以使用正确的 gcc 路径覆盖它:

export LDSHARED="/correct/path/to/gcc -pthread -shared"
Run Code Online (Sandbox Code Playgroud)

然后重建扩展,它应该可以工作。

第二种解决方案(可能更好)

配置LDSHARED是从lib/python2.7/_sysconfigdata.py构建时生成的文件中检索的。

您可以修改此文件,这样就无需设置环境变量。


调试技巧

设置DISTUTILS_DEBUG环境以激活调试模式,这样您就可以在编译失败时看到回溯。