- integral.f90文件
function integral(func, a, b, step)
real(8), external :: func !external不寫也可以,不過還是標明一下這是函數
real(8) :: a, b, step, integral
real(8) :: x
x = a
integral = 0.
do while(x < b)
integral = integral + func(x)
x = x + step
end do
integral = integral * step
end function integral
- test.c文件
#include<stdio.h>
#include<math.h>
double integral_(double(*)(double*), double*, double*, double*);
double circle(double *x){
return sqrt(100. - (*x)*(*x));
}
int main(){
double a=0., b=10., step=1e-5;
printf("%f", integral_(circle, &a, &b, &step)/25.);
}
- Makefile
test : test.c integral.f90
gfortran -c integral.f90 -o integral.o
gcc -c test.c -o test.o
gfortran -o test.exe test.o integral.o
其中c調用了fortran的integral
函數,而integral
函數的一個參數是c函數,在integral
函數中又調用了c函數。這樣看來,其實gcc和gfortran編譯成的.o
文件其實本質上是一樣的,鏈接之後,這些函數應該都可以隨便用。不過c語言中的函數在.o
文件中名字不變,而fortran的函數在.o
文件中被加了一個下劃線,所以在test.c文件中使用的是integral_
函數。當然,如果是c++函數,因爲要處理重載,名字就會改的亂七八糟了。
可惜的是,fortran中調用的c函數參數必須是指針,這樣我的這個integral
函數就不能對對c的內置函數做積分了。