在 CentOS 上实现 Fortran 与 C 的混合编程,核心思路是:
利用两种语言对底层函数调用和符号命名的约定,通过编译器生成目标文件后链接在一起。
下面从 原理 → 编译方法 → 示例 → 常见坑 四部分说明。
C:函数名基本不变
void foo(int a);
符号:foo
Fortran(gfortran):默认会 变成小写并加下划线
subroutine foo(a)
符号:foo_ 或 foo(取决于编译选项)
sudo yum install gcc gcc-gfortran
检查版本:
gcc --version
gfortran --version
subroutine foo(a, b, c)
integer, intent(in) :: a, b
integer, intent(out) :: c
c = a + b
end subroutine foo
#include <stdio.h>
extern void foo_(int *a, int *b, int *c);
int main() {
int a = 3, b = 4, c;
foo_(&a, &b, &c);
printf("c = %d\n", c);
return 0;
}
gfortran -c foo.f90
gcc main.c foo.o -lgfortran -o test
./test
#include <stdio.h>
void bar(int *n) {
printf("n = %d\n", *n);
}
program main
integer :: n
n = 10
call bar(n)
end program main
gcc -c bar.c
gfortran main.f90 bar.o -o test
./test
这是 现代 Fortran 标准做法,不受编译器符号规则影响。
program main
use iso_c_binding
interface
subroutine bar(n) bind(c)
use iso_c_binding
integer(c_int), value :: n
end subroutine bar
end interface
call bar(10)
end program main
#include <stdio.h>
void bar(int n) {
printf("n = %d\n", n);
}
-lgfortrangcc main.c foo.o # ❌
gcc main.c foo.o -lgfortran # ✅
C 是行优先,矩阵运算要小心。
Fortran 字符串会附带长度参数,建议用 iso_c_binding + c_char。
| 方式 | 推荐度 | 说明 |
|---|---|---|
| 手动加下划线 | ❌ | 不跨平台 |
iso_c_binding |
✅✅✅ | 标准、稳定 |
| 直接链接 | ✅ | 适合老代码 |
如果你有 具体场景(数值计算 / MPI / BLAS / LAPACK / 老代码迁移),我可以给你更针对性的示例。