2013-05-21 191 views
1

我想用fortran调用C函数(需要这个用于项目)。因此首先尝试通过fortran简单地调用一个非参数化的无效函数。从Fortran调用C函数

请帮助我解决给定代码中的以下错误。

C代码的矩阵乘法:

#include <stdio.h> 


extern "C" 

{ void __stdcall mat(); 
} 


void mat() 
{ 
int m, n, p, q, c, d, k, sum = 0; 

    printf("Enter the number of rows and columns of first matrix\n"); 
scanf("%d%d", &m, &n); 

    int first[m][n]; 

    printf("Enter the elements of first matrix\n"); 

    for ( c = 0 ; c < m ; c++) 
    for (d = 0 ; d < n ; d++) 
    scanf("%d", &first[c][d]); 

    printf("Enter the number of rows and columns of second matrix\n"); 
    scanf("%d%d", &p, &q); 

    int second[p][q]; 

if (n != p) 
    printf("Matrices with entered orders can't be multiplied with each other.\n"); 
else 
{ 
    printf("Enter the elements of second matrix\n"); 

    for (c = 0 ; c < p ; c++) 
    for (d = 0 ; d < q ; d++) 
    scanf("%d", &second[c][d]); 

    int multiply[m][q]; 

    for (c = 0 ; c < m ; c++) 
{ 
    for (d = 0 ; d < q ; d++) 
    { 
    for (k = 0 ; k < p ; k++) 
    { 
     sum = sum + first[c][k]*second[k][d]; 
    } 

    multiply[c][d] = sum; 
    sum = 0; 
    } 
} 

    printf("Product of entered matrices:-\n"); 

    for (c = 0 ; c < m ; c++) 
    { 
    for (d = 0 ; d < q ; d++) 
     printf("%d\t", multiply[c][d]); 

    printf("\n"); 
    } 
} 

} 

    int main() 
{ 
mat(); 
return 0; 
} 

而且,从调用FORTRAN函数垫,我写的代码是:

program mat_mult !This is a main program. 

    call mat() 
    stop 
    end 

上执行的C文件我得到以下错误:

matrix_mult.c:5:错误:期望的标识符或'('在字符串常量之前

在使用F77编译器执行Fortran文件,我得到以下错误:

/tmp/ccQAveKc.o:在功能MAIN__': matrix_mult.f:(.text+0x19): undefined reference to mat_” collect2:LD返回1个退出状态

请帮助我确定错误/正确的代码。 谢谢。

回答

1

第一

1)我假设你使用的是C99编译器,因为你写的C代码将无法在C89编译器的工作,有几件事情。

2)extern“C”用于C++程序:不是C程序。

不确定你使用的编译器。假设你使用gcc和gfortran,因为它看起来像你在基于Linux的系统上。

gcc只是为符号添加了一个前导_:所以mat变成了_mat。 gfortran在符号中增加了一个前导_和尾随_:所以mat变成_mat _。

为了使C和Fortran说话

一)从C代码

b)拆卸的extern “C” 声明中取出的主要功能。这是一个C++声明,它告诉编译器该例程不应该有任何名称混乱。 c)由于您没有任何参数,只需假设_ cdecl并将void mat()更改为void mat()。如果你必须使用stdcall,那么你需要使用--enable-stdcall-fixup进行编译。如果Fortran程序必须将参数传递给C程序,则需要stdcall,但这是一个不同的球类游戏。相反_mat _中,编译器生成垫@ 0

d)你的C例程将现在看起来像

#include <stdio.h> 
void mat_() 
{ 
    ... 
} 

/* No main */ 

E)由于常规垫不会在Fortran代码中声明,编译器需要知道它是外部的。

program mat_mult 
external mat 
call mat() 
stop 
end 

F)编译和链接(比如C语言程序被称为mat.c和Fortran程序被称为matmul.f)

gcc -g -c mat.c 
gfortran -g matmul.f mat.o -o matmul 

有可能会被评论的整个负载,建议你使用F2003或者F2008,但是如果你被告知你必须使用F77,那么你必须使用F77。