Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
459 views
in Technique[技术] by (71.8m points)

compilation - Calling C function/subroutine in Fortran code

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
", (*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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...