在 Fortran 代码中调用 C 函数/子例程 [英] Calling C function/subroutine in Fortran code

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

问题描述

我正在尝试编译和链接调用 c 子例程的 Fortran 代码:

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

Fortran 代码:

Fortran code:

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

C 代码:

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
", (*a), (*b), c );
}

我在windows环境下使用如下命令编译链接.

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

我收到以下错误:

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.

推荐答案

您需要在 Fortran 主程序的规范部分中为 C 函数提供一个接口主体,它告诉 Fortran 编译器名称 addnums 是一个 C 函数.类似的东西:

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

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

(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 函数/子例程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆