在 CentOS 上实现 Fortran 与 C 的混合编程,核心问题是:函数命名规则、参数传递方式、编译链接顺序。下面按“能跑起来的最小示例 → 原理 → 常见问题”来讲。
#include <stdio.h>
void hello_from_c_(int *n) {
printf("C says: n = %d\n", *n);
}
⚠️ 注意:
hello_from_c_后面有下划线,这是 gfortran 的默认命名规则
program main
implicit none
integer :: n
n = 10
call hello_from_c(n)
end program main
gcc -c hello_c.c
gfortran main.f90 hello_c.o -o test
./test
subroutine foo(n)
implicit none
integer :: n
print *, "Fortran says: n =", n
end subroutine foo
#include <stdio.h>
void foo_(int *n);
int main() {
int n = 5;
foo_(&n);
return 0;
}
gfortran -c foo.f90
gcc main.c foo.o -lgfortran -o test2
./test2
| 编译器 | Fortran 函数 sub foo |
|---|---|
| gfortran | foo_ |
| ifort | foo 或 foo_ |
✅ 最稳妥方式:用 iso_c_binding(推荐)
module mymod
use iso_c_binding
implicit none
contains
subroutine foo(n) bind(C, name="foo")
integer(c_int), value :: n
print *, "Fortran n =", n
end subroutine
end module
void foo(int n);
int main() {
foo(7);
return 0;
}
✅ 不需要下划线 ✅ 跨平台、跨编译器
| Fortran | C |
|---|---|
| 默认传引用 | 传指针 |
value 属性 |
传值 |
| 数组 | 指针 |
| 字符串 | character(len=1) 数组 |
undefined reference to `foo_'
✅ 解决:
-lquadmath -lgfortran
gfortran a.f90 b.c -o exe
或
gcc main.c fortran.o -lgfortran
Fortran 默认传引用
call foo(n) ! 实际传 &n
C 函数名必须有下划线(老方式)
忘了链接 -lgfortran
Fortran 数组是列优先(C 是行优先)
✅ 新项目:用 iso_c_binding
✅ 老代码:接受 _ 命名规则
✅ CentOS:默认 gcc + gfortran
如果你有:
ifort 还是 gfortran我可以给你 针对你项目的混合编程模板。