面试题答案
一键面试Fortran 代码示例
program call_c_function
implicit none
interface
integer function add_numbers(a, b) bind(c, name='add_numbers')
use iso_c_binding
integer(c_int), value :: a
integer(c_int), value :: b
end function add_numbers
end interface
integer :: result
integer, parameter :: a = 3
integer, parameter :: b = 5
result = add_numbers(a, b)
print *, 'The sum of ', a,'and ', b,'is: ', result
end program call_c_function
C 语言代码示例
#include <stdio.h>
#include <stdint.h>
// C 函数实现两个整数相加
int32_t add_numbers(int32_t a, int32_t b) {
return a + b;
}
关于编译器兼容性
- 数据类型:使用
iso_c_binding
模块中的c_int
等类型,以确保 Fortran 和 C 语言之间的数据类型匹配。c_int
通常与 C 语言中的int
相对应,并且在不同编译器下更具可移植性。 - 绑定声明:使用
bind(c)
声明 Fortran 接口,这告诉 Fortran 编译器该函数遵循 C 语言的调用约定。name='add_numbers'
明确指定了 C 函数的名称,以避免在不同编译器下可能出现的名称修饰问题。 - 编译链接:在编译时,确保使用支持 Fortran 和 C 混合编程的编译器。例如,GNU Fortran(gfortran)和 GCC 可以很好地配合使用。编译时,需要将 Fortran 源文件和 C 源文件一起编译链接,例如:
gfortran -c call_c_function.f90 gcc -c add_numbers.c gfortran call_c_function.o add_numbers.o -o call_c_function.exe
不同编译器在具体选项和细节上可能略有不同,但基本思路是相似的,通过明确数据类型、调用约定和名称匹配,来确保在不同编译器下的兼容性。