在 Ubuntu 上交叉编译 Fortran 程序,核心思路是:
安装目标平台的交叉编译工具链(含 gfortran)→ 用交叉 gfortran 编译 → 处理库依赖。
下面按常见场景说明。
交叉编译 = 在 x86_64 Ubuntu 上,编译出 ARM / RISC-V / Windows 等平台上可运行的 Fortran 程序。
关键工具:
x86_64-linux-gnu-gfortranarm-linux-gnueabihf-gfortranaarch64-linux-gnu-gfortranx86_64-w64-mingw32-gfortran(Windows)sudo apt update
sudo apt install gfortran-arm-linux-gnueabihf
使用:
arm-linux-gnueabihf-gfortran hello.f90 -o hello_arm
sudo apt install gfortran-aarch64-linux-gnu
使用:
aarch64-linux-gnu-gfortran hello.f90 -o hello_aarch64
sudo apt install gfortran-mingw-w64
使用:
x86_64-w64-mingw32-gfortran hello.f90 -o hello.exe
sudo apt install gfortran-riscv64-linux-gnu
hello.f90
program hello
print *, "Hello from Fortran!"
end program hello
编译:
aarch64-linux-gnu-gfortran hello.f90 -o hello
file hello
# hello: ELF 64-bit LSB executable, ARM aarch64
需要确保库也是 交叉编译的
aarch64-linux-gnu-gfortran main.f90 \
-L/path/to/arm/lib \
-lmylib
sudo apt install liblapack-dev-arm64-cross
或自己交叉编译 OpenBLAS。
arm.cmakeset(CMAKE_SYSTEM_NAME Linux)
set(CMAKE_C_COMPILER aarch64-linux-gnu-gcc)
set(CMAKE_Fortran_COMPILER aarch64-linux-gnu-gfortran)
set(CMAKE_FIND_ROOT_PATH /usr/aarch64-linux-gnu)
构建:
cmake -DCMAKE_TOOLCHAIN_FILE=arm.cmake ..
make
which aarch64-linux-gnu-gfortran
没有就安装对应包。
错误示例:
skipping incompatible /usr/lib/libxxx.so
✅ 必须用 交叉编译的库
交叉编译的程序 不能在 Ubuntu 直接运行
./hello_aarch64
# Exec format error
需用 QEMU 或目标板:
qemu-aarch64 ./hello_aarch64
| 目标平台 | 安装命令 |
|---|---|
| ARM32 | gfortran-arm-linux-gnueabihf |
| ARM64 | gfortran-aarch64-linux-gnu |
| Windows | gfortran-mingw-w64 |
| RISC-V | gfortran-riscv64-linux-gnu |
如果你能告诉我:
我可以直接给你 完整可跑的编译命令或工程模板。