在Ubuntu上,Fortran和C可以通過使用外部接口(external interface)或者調用C語言編寫的共享庫(shared library)進行交互。以下是一些基本步驟來實現Fortran和C之間的交互:
編寫Fortran代碼并聲明外部接口
在Fortran代碼中,你需要使用iso_c_binding模塊來聲明與C語言兼容的數據類型,并使用bind(C)屬性來聲明外部接口。
! example.f90
module example_mod
use iso_c_binding, only: c_int, c_double
implicit none
interface
subroutine c_function(x, y) bind(C, name="c_function")
import c_int, c_double
real(c_double), intent(in) :: x
integer(c_int), intent(out) :: y
end subroutine c_function
end interface
contains
subroutine fortran_function(x, y)
real(c_double), intent(in) :: x
integer(c_int), intent(out) :: y
call c_function(x, y)
end subroutine fortran_function
end module example_mod
編寫C代碼并編譯為共享庫
編寫C代碼并使用gcc編譯器將其編譯為共享庫(.so文件)。
// example.c
#include <stdio.h>
void c_function(double x, int *y) {
printf("C function called with x = %f\n", x);
*y = (int)x;
}
使用以下命令編譯C代碼:
gcc -fPIC -c example.c -o example.o
gcc -shared -o libexample.so example.o
在Fortran代碼中調用共享庫
在Fortran代碼中,使用use語句導入模塊,并調用共享庫中的函數。
! main.f90
program main
use example_mod
implicit none
real(c_double) :: x
integer(c_int) :: y
x = 3.14
call fortran_function(x, y)
print *, "Fortran received y =", y
call c_function(x, y)
print *, "Fortran received y =", y
end program main
編譯并運行Fortran程序
使用gfortran編譯器編譯Fortran代碼,并鏈接共享庫。
gfortran -o main main.f90 -L. -lexample
LD_LIBRARY_PATH=. ./main
編寫C代碼并編譯為共享庫
編寫C代碼并使用gcc編譯器將其編譯為共享庫(.so文件)。
// example.c
#include <stdio.h>
void c_function(double x, int *y) {
printf("C function called with x = %f\n", x);
*y = (int)x;
}
使用以下命令編譯C代碼:
gcc -fPIC -c example.c -o example.o
gcc -shared -o libexample.so example.o
在Fortran代碼中調用共享庫
在Fortran代碼中,使用use語句導入模塊,并調用共享庫中的函數。
! main.f90
program main
implicit none
real(c_double) :: x
integer(c_int) :: y
interface
subroutine c_function(x, y) bind(C, name="c_function")
import c_double, c_int
real(c_double), intent(in) :: x
integer(c_int), intent(out) :: y
end subroutine c_function
end interface
x = 3.14
call c_function(x, y)
print *, "Fortran received y =", y
end program main
編譯并運行Fortran程序
使用gfortran編譯器編譯Fortran代碼,并鏈接共享庫。
gfortran -o main main.f90 -L. -lexample
LD_LIBRARY_PATH=. ./main
通過以上兩種方法,你可以在Ubuntu上實現Fortran和C之間的交互。選擇哪種方法取決于你的具體需求和偏好。