本文介绍了在Fortran代码中调用C函数/子例程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



Fortran代码:

<$ p $ b $ 程序加法器
整数a,b
a = 1
b = 2
调用addnums(a,b)
stop
结束程序



C代码:

 {
int c =(* a)+(* b); / *将指针转换为值,然后添加它们* /
printf(%i和%i的总和为%i \ n,(* a),(* b),c);
}

我使用以下命令在Windows环境下进行编译和链接。

  ifort -c adder.f 
cl -c addnums.c
ifort -o add adder.obj addnums。 obj

我收到以下错误消息:

<$微软(R)增量链接器版本8.00.50727.762
版权所有(C)微软公司。版权所有。
-out:add.exe
-subsystem:console
adder.obj
addnums.obj
adder.obj:错误LNK2019:无法解析的外部符号ADDNUMS在函数中引用MAIN__
add.exe:致命错误LNK1120:1无法解析的外部

请帮我解决这个问题问题?感谢。

解决方案

您需要为Fortran主程序的规范部分中的C函数提供一个接口体, Fortran编译器名称 addnums 是一个C函数。例如:

  INTERFACE 
SUBROUTINE addnums(a,b)BIND(C)
USE,INTRINSIC :: ISO_C_BINDING,只有:C_INT
IMPLICIT NONE
INTEGER(C_INT):: a,b
END SUBROUTINE addnums
END INTERFACE

(对于那些没有特殊选项的编译器,默认类型的整数与C_INT相同 - 但显式说明整数KIND有助于保护您编译器/平台或编译选项的变化。)


I am attempting to compile and link a Fortran code calling c subroutine:

Fortran code:

program adder
integer a,b
a=1
b=2
call addnums(a,b)
stop
end program

C code:

void addnums( int* a, int* b )
{
    int c = (*a) + (*b);  /* convert pointers to values, then add them */
    printf("sum of %i and %i is %i\n", (*a), (*b), c );
}

I used the following commands to compile and link in windows environment.

ifort -c adder.f
cl -c addnums.c
ifort -o add adder.obj addnums.obj

I get the following error:

Microsoft (R) Incremental Linker Version 8.00.50727.762
Copyright (C) Microsoft Corporation.  All rights reserved.
-out:add.exe
-subsystem:console
adder.obj
addnums.obj
adder.obj : error LNK2019: unresolved external symbol ADDNUMS referenced in function MAIN__
add.exe : fatal error LNK1120: 1 unresolved externals

Please help me resolve this issue? Thanks.

解决方案

You need to provide an interface body for the C function inside the specification part of the Fortran main program that tells the Fortran compiler that the name addnums is a C function. Something like:

INTERFACE
  SUBROUTINE addnums(a, b) BIND(C)
    USE, INTRINSIC :: ISO_C_BINDING, ONLY: C_INT
    IMPLICIT NONE
    INTEGER(C_INT) :: a, b
  END SUBROUTINE addnums
END INTERFACE

(With those compilers on that platform without special options the default kind of integer is the same as C_INT - but being explicit about the integer KIND helps protect you if compiler/platform or compile options change.)

这篇关于在Fortran代码中调用C函数/子例程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-06 19:01