ubuntu

Ubuntu中Fortran如何调用C函数

小樊
42
2025-04-13 13:44:33
栏目: 智能运维

在Ubuntu中,Fortran可以通过使用ISO C Binding来调用C函数。以下是一个简单的示例,展示了如何在Fortran代码中调用C函数。

首先,创建一个名为example.c的C文件,包含一个简单的C函数:

#include <stdio.h>

void hello_from_c() {
    printf("Hello from C!\n");
}

接下来,创建一个名为example.f90的Fortran文件,用于调用上面创建的C函数:

! example.f90
program main
    use iso_c_binding, only: c_void
    implicit none

    interface
        subroutine hello_from_c() bind(c, name="hello_from_c")
            import c_void
            ! No arguments and no return value
        end subroutine hello_from_c
    end interface

    call hello_from_c()

end program main

在这个Fortran文件中,我们使用了iso_c_binding模块来定义与C语言兼容的数据类型和接口。bind(c, name="hello_from_c")子句指定了我们要调用的C函数的名称。

现在,编译这两个文件并将它们链接在一起。在终端中,运行以下命令:

gfortran -c example.c
gfortran -c example.f90
gfortran example.o example.o -o example

这将生成一个名为example的可执行文件。运行它,你将看到以下输出:

Hello from C!

这就是在Ubuntu中使用Fortran调用C函数的方法。请注意,这个示例仅适用于简单的函数调用。对于更复杂的函数,可能需要处理数据类型转换和内存管理等问题。

0
看了该问题的人还看了