温馨提示×

ubuntu python如何交叉编译

小樊
83
2026-09-25 17:26:02
栏目: 编程语言

在 Ubuntu 上用 Python 进行交叉编译,通常指两种情况:

  1. 交叉编译 Python 解释器本身(比如给 ARM 板子编译 Python)
  2. 在 Ubuntu 上为其他平台交叉编译 Python 扩展(.so / 轮子)

下面分别说明常见做法。


一、交叉编译 Python 解释器(以 ARM 为例)

1. 安装交叉编译工具链

sudo apt update
sudo apt install gcc-arm-linux-gnueabihf g++-arm-linux-gnueabihf

2. 下载 Python 源码

wget https://www.python.org/ftp/python/3.11.6/Python-3.11.6.tgz
tar xf Python-3.11.6.tgz
cd Python-3.11.6

3. 配置交叉编译

./configure \
  --host=arm-linux-gnueabihf \
  --build=x86_64-linux-gnu \
  --prefix=/opt/python-arm \
  --enable-shared \
  --without-ensurepip

4. 编译并安装

make -j$(nproc)
make install

生成的 Python 就在 /opt/python-arm


二、交叉编译 Python C 扩展(推荐方式)

方法 1:使用 crossenv(最推荐)

适合已有目标平台 Python

pip install crossenv
crossenv /path/to/target/python3 crossenv
source crossenv/bin/activate

pip install your_package

✅ 自动处理 setup.py / pyproject.toml


方法 2:使用 zig + cibuildwheel(现代方案)

pip install cibuildwheel
CIBW_ARCHS=armv7l cibuildwheel

方法 3:手动指定交叉编译器

export CC=arm-linux-gnueabihf-gcc
export CROSS_COMPILE=arm-linux-gnueabihf-

python setup.py build_ext --plat-name=linux-armv7l

三、交叉编译 Python 轮子(wheel)

使用 maturin(Rust + Python)

maturin build --target armv7-unknown-linux-gnueabihf

使用 auditwheel

auditwheel repair xxx.whl

四、常见问题

Q1: cannot run test program while cross compiling

在 configure 加:

ac_cv_file__dev_ptmx=yes
ac_cv_file__dev_ptc=no

Q2: pip 装不上 C 扩展

✅ 用 crossenv 或预编译 wheel


五、总结建议

场景 推荐方案
编译 Python 解释器 ./configure --host
编译 C 扩展 crossenv
构建 wheel cibuildwheel
Rust 扩展 maturin

如果你能说明:

  • 目标平台(ARM / RISCV / aarch64)
  • 是否要编译 Python 本身
  • 是否用 pip / setup.py / Rust

我可以给你精确命令。

0 踩