[英]C Wrapper Calling Fortran Functions
我正在嘗試編寫一個C包裝器來調用Fortran模塊中的一組函數。 我從一些基本的東西開始,但我遺漏了一些重要的東西。
我試過附加/前置不同數量的下划線。 我也試過用gcc而不是gfortran連接。 我在下面顯示的內容給出了最簡單的錯誤。
我正在使用運行Yosemite 10.10.3的Mac,GNU Fortran 5.1.0以及Xcode附帶的C編譯器。
main.c中
#include "stdio.h"
int main(void)
{
int a;
float b;
char c[30];
extern int _change_integer(int *a);
printf("Please input an integer: ");
scanf("%d", &a);
printf("You new integer is: %d\n", _change_integer(&a));
return 0;
}
intrealstring.f90
module intrealstring
use iso_c_binding
implicit none
contains
integer function change_integer(n)
implicit none
integer, intent(in) :: n
integer, parameter :: power = 2
change_integer = n ** power
end function change_integer
end module intrealstring
這是我正在編譯的方式,以及錯誤:
$ gcc -c main.c
$ gfortran -c intrealstring.f90
$ gfortran main.o intrealstring.o -o cwrapper
Undefined symbols for architecture x86_64:
"__change_integer", referenced from:
_main in main.o
ld: symbol(s) not found for architecture x86_64
collect2: error: ld returned 1 exit status
$
你必須將fortran綁定到c:
module intrealstring
use iso_c_binding
implicit none
contains
integer (C_INT) function change_integer(n) bind(c)
implicit none
integer (C_INT), intent(in) :: n
integer (C_INT), parameter :: power = 2
change_integer = n ** power
end function change_integer
end module intrealstring
您的c文件必須修改如下:
#include "stdio.h"
int change_integer(int *n);
int main(void)
{
int a;
float b;
char c[30];
printf("Please input an integer: ");
scanf("%d", &a);
printf("You new integer is: %d\n", change_integer(&a));
return 0;
}
你可以這樣做:
$ gcc -c main.c
$ gfortran -c intrealstring.f90
$ gfortran main.o intrealstring.o -o cwrapper
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.