Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从Fortran调用C函数时GNU编译器分段错误,但英特尔编译器运行良好_Fortran - Fatal编程技术网

从Fortran调用C函数时GNU编译器分段错误,但英特尔编译器运行良好

从Fortran调用C函数时GNU编译器分段错误,但英特尔编译器运行良好,fortran,Fortran,我通过以下链接学会了从Fortran调用C函数 当使用GNU编译器编译时,我将call_fc中的int更改为double(相应的代码也会更改)时,我遇到了一个“SIGSEGV”问题,而英特尔编译器则没有问题 C代码和Fortran代码如下所示: ///要从Fortran调用的C函数 #include "stdio.h" #include "math.h" void call_fc(double *(*x), int s) { double *y = malloc(s*sizeof(d

我通过以下链接学会了从Fortran调用C函数

当使用GNU编译器编译时,我将
call_fc
中的
int
更改为
double
(相应的代码也会更改)时,我遇到了一个“SIGSEGV”问题,而英特尔编译器则没有问题

C代码和Fortran代码如下所示:

///要从Fortran调用的C函数

#include "stdio.h"
#include "math.h"

void call_fc(double *(*x), int s)
{
    double *y = malloc(s*sizeof(double));
    int i;
    for(i=0; i < s; i++)
    {
        y[i]= sin((double)i);//(double)((i+1)*(i+1));
    }
    *x = y;
}
对于GNU编译器(线程模型:posix gcc版本4.9.2 20150212(红帽4.9.2-6)(gcc) ),我使用以下命令来编译它:

gcc -c test.c -o testc.o
gfortran -c test.f90 -o testf.o
gfortran testc.o testf.o -o testg.x
./testg.x

顺便说一下,“英特尔编译器”的命令有:

icc -c test.c -o testc.o
ifort -c test.f90 -o testf.o
ifort testc.o testf.o -o testi.x
./testi.x
请帮助我为GNU编译器提供正确的选项,或者修改两个编译器都能接受的程序。多谢各位

修正后 ///测试c


程序中存在多个问题。第一个是C。是否禁用编译器警告?我的gcc抱怨说

> gfortran value.c value.f90
value.c: In function ‘call_fc’:
value.c:7:17: warning: incompatible implicit declaration of built-in function ‘malloc’ [enabled by default]
     double *y = malloc(s*sizeof(double));
             ^
这可能不会在一台计算机上导致崩溃,但很容易在其他地方导致崩溃

你应该包括

#include <stdlib.h>

因为C函数要求参数按值。另一个参数没有
,因为它是一个通过引用传递的指针,而C有一个指向指针的指针。

整数必须通过
传递,可能存在一些重复的问题。请尝试
integer(c_int),value::s
不确定是否立即解决了完全相同的问题!非常感谢弗拉基米尔F!非常感谢您指出这些问题!令人惊叹的!
PROGRAM FORT_C
   use iso_c_binding
   IMPLICIT NONE

   interface
      subroutine call_fc(pX,s) bind(C,name='call_fc')
         import
         integer(c_int),value :: s
         type(c_ptr)          :: pX
      end subroutine
   end interface

   integer(c_int)           :: i
   integer(c_int)           :: s
   real(c_double), pointer  :: X(:)
   type(C_ptr)              :: pX

   s = 10
   call call_fc(pX,s)
   call c_f_pointer(pX,X,(/s/))

   do i=1,s
      write(*,*)  i, x(i)
   end do

END program
> gfortran value.c value.f90
value.c: In function ‘call_fc’:
value.c:7:17: warning: incompatible implicit declaration of built-in function ‘malloc’ [enabled by default]
     double *y = malloc(s*sizeof(double));
             ^
#include <stdlib.h>
integer(c_int), value :: s