在Ubuntu中,Fortran可以通过使用ISO C Binding来调用C语言函数。以下是一个简单的示例,展示了如何在Fortran代码中调用C语言函数。
首先,创建一个C语言源文件(例如example.c
),并包含一个简单的函数:
#include <stdio.h>
void hello_from_c() {
printf("Hello from C!\n");
}
接下来,创建一个Fortran源文件(例如example.f90
),并使用iso_c_binding
模块来声明和调用C函数:
program call_c_function
use iso_c_binding, only: c_void
implicit none
interface
subroutine hello_from_c() bind(c, name="hello_from_c")
import c_void
end subroutine hello_from_c
end interface
! 调用C函数
call hello_from_c()
end program call_c_function
在这个例子中,我们使用bind(c, name="hello_from_c")
来指定C函数的名称,以便Fortran代码可以正确地找到并调用它。
现在,编译C和Fortran源文件,并将它们链接在一起。在终端中,运行以下命令:
gfortran -c example.c
gfortran -c example.f90
gfortran example.o -o example
这将生成一个名为example
的可执行文件。运行它,你将看到以下输出:
Hello from C!
这就是在Ubuntu中使用Fortran调用C语言函数的方法。请注意,这个例子中的C函数没有参数和返回值。如果你需要传递参数或处理返回值,你需要在Fortran接口块中相应地声明它们。