温馨提示×

centosfortran和c如何混合编

小樊
51
2026-10-06 06:00:33
栏目: 智能运维

在 CentOS 上实现 Fortran 与 C 的混合编程,核心问题是:函数命名规则、参数传递方式、编译链接顺序。下面按“能跑起来的最小示例 → 原理 → 常见问题”来讲。


一、最简示例(CentOS 可直接编译)

1️⃣ Fortran 调用 C 函数

C 代码(hello_c.c)

#include <stdio.h>

void hello_from_c_(int *n) {
    printf("C says: n = %d\n", *n);
}

⚠️ 注意:hello_from_c_ 后面有下划线,这是 gfortran 的默认命名规则

Fortran 代码(main.f90)

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

2️⃣ C 调用 Fortran 函数

Fortran 代码(foo.f90)

subroutine foo(n)
    implicit none
    integer :: n
    print *, "Fortran says: n =", n
end subroutine foo

C 代码(main.c)

#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

二、核心原理(必须知道)

1️⃣ 命名规则(非常重要)

编译器 Fortran 函数 sub foo
gfortran foo_
ifort foo 或 foo_

✅ 最稳妥方式:用 iso_c_binding(推荐)


2️⃣ 推荐方式:ISO_C_BINDING(现代 Fortran)

Fortran(foo.f90)

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

C(main.c)

void foo(int n);

int main() {
    foo(7);
    return 0;
}

✅ 不需要下划线 ✅ 跨平台、跨编译器


三、参数传递规则

Fortran C
默认传引用 传指针
value 属性 传值
数组 指针
字符串 character(len=1) 数组

四、编译链接注意事项(CentOS)

常见链接错误

undefined reference to `foo_'

✅ 解决:

-lquadmath -lgfortran

推荐编译顺序

gfortran a.f90 b.c -o exe

或

gcc main.c fortran.o -lgfortran

五、常见坑(CentOS 特别容易踩)

  1. Fortran 默认传引用

    call foo(n)   ! 实际传 &n
    
  2. C 函数名必须有下划线(老方式)

  3. 忘了链接 -lgfortran

  4. Fortran 数组是列优先(C 是行优先)


六、总结建议

✅ 新项目:用 iso_c_binding
✅ 老代码:接受 _ 命名规则
✅ CentOS:默认 gcc + gfortran


如果你有:

  • 具体代码片段
  • 用的是 ifort 还是 gfortran
  • 是在 数值计算 / MPI / OpenMP 场景

我可以给你 针对你项目的混合编程模板。

0 踩