2015-05-19 83 views
3

我正在尝试编写一个C封装程序来调用Fortran模块中的一组函数。我从一些基本的东西开始,但我错过了一些重要的东西。C封装程序调用Fortran函数

我试着追加/预先设置不同数目的下划线。我也尝试用gcc而不是gfortran链接。我在下面显示的是最简单的错误。

我正在运行Yosemite 10.10.3,GNU Fortran 5.1.0的Mac和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 
$ 
+1

错误建议你的混合32位和64位代码? – cjb110

+0

请务必使用标签[tag:fortran],仅在您想要强调不需要任何更新的标准版本时才为各个版本使用标签。 –

回答

3

你必须绑定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 
+0

也许不是,C_INT更好。我编辑 – LPs

+0

谢谢弗拉基米尔。你的解决方案有效在Fortran函数change_integer中,参数“power”是本地的。对C的绑定仍然是必要的,还是将所有声明绑定到C都是一种很好的编程习惯? – leoleson

+0

我想你是在问我你的问题。是的,你可以避免绑定权力变量,因为是本地的。我在编写包装时总是使用绑定。避免在必须的地方忘记绑定是个人规则。请将答案设为正确,以避免其他人浪费时间。 – LPs