C与Fortran都是应用广泛的语言,由于二者语言特性的不同,应用的场合很有差异。C语言通常用于系统软件和一些应用软件的开发,而Fortran在高性能应用领域有很好的应用。对于通常的用户,接促C语言的较多,但是,C语言的开发者,有时还想利用高效的Fortran 数据包 或者是Fortran语言的开发者想借用C提供的强大辅助功能,为此,为了方便大家对二语言相互调用的学习。这里给出了一些简单的入门性技术介绍。 1. C 调用Fortran 编辑Fortran 源文件 add.f95 subroutine add(a, b, c) implicit none real:: a, b, c ! ! the add routine ! c = a b ! c = a b write(*,*) a, ’ ’, b, ’=’, c return end subroutine add 这里部介绍Fortran的语法格式,add.f95的功能是建立一个add routine 也就是函数。 编译 add.f95 f95 -o add.o -c add.f95 编辑C 主程序main.c 1 #include 2 3 extern void add_(float *a, float *b, float *c). 4 5 int main(int argc, char *argvs[]) 6 { 7 float a, b, c. 8 a = 5.0. 9 b = 7.0. 10 add_(&.a, &.b, &.c). 11 12 return 0. 13 } 3: 声明你要调用的函数,这里注意,是add_,调用的时候用指针,即变量地址,你应该明白了Fortran的调用是改变参数值的。 10:调用fortran函数 编译与执行 #gfortran -o main main.c add.o #./main 5.000000 7.000000 = 12.00000 NOTES. if you use the gcc tool, it will generate error #gcc -o main main.c add.o add.o: In function `add_’: add.f95:(.text 0x4c): undefined reference to `_gfortran_st_write’ add.f95:(.text 0x69): undefined reference to `_gfortran_transfer_real’ add.f95:(.text 0x87): undefined reference to `_gfortran_transfer_character’ add.f95:(.text 0xa4): undefined reference to `_gfortran_transfer_real’ add.f95:(.text 0xc2): undefined reference to `_gfortran_transfer_character’ add.f95:(.text 0xdf): undefined reference to `_gfortran_transfer_real’ add.f95:(.text 0xed): undefined reference to `_gfortran_st_write_done’ collect2: ld returned 1 exit status Some Wrong with your PATH for you gcc library OK! you are clever and has known how call fortran routines in the C progaram. Next part I show you how to call C routines in the Fortran program! 2, Fortran 调用 C 函数 编辑C源码add.c 1 #include 2 3 void add_(float *a, float *b, float *c) 4 { 5 *c = *a *b. 6 printf("%f %f = %f\n", *a, *b, *c). 7 } Notes The funtion name "add_" 编译源代码 # gcc -o add.o -c add.c 编辑fortran 主程序main.f95,编译和执行 1 PROGRAM MAIN 2 implicit none 3 real:: i, j, k 4 ! 5 ! The first fortran program 6 ! 7 i = 5.0 8 j = 8.0 9 call add(i, j, k) 10 stop 11 end program MAIN NOTE 9 line # gfortran -o main main.f95 add.o (or f95 -o main main.f95 add.o) # ./main 5.000000 8.000000 = 13.000000 OK. If you reach here, congratulations, you have learned how to call routines between C and fortran!