- 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的内置函数做积分了。