Write C function that returns int to Fortran

亡梦爱人 提交于 2019-12-11 12:15:01

问题


Ultimately I am trying to write an IPC calculator making use of Fortran to calculate and C to pass the data between the two Fortran programs. When I am done it will hopefully look like:

Fortran program to pass input -> Client written in C -> Server written in C -> Fortran program to calculate input and pass ans back

The C client/server part is done, but at the moment I am stuck trying to write a program that takes input in a Fortran program, passes it to a C program that calculates the answer. However, I see som weird behavior.

Fortran program

program calculator
    !implicit none

    ! type declaration statements
    integer x
    x = 1

    ! executable statements
    x = calc(1,1)
    print *, x

end program calculator

C function

int calc_(int *a, int *b ) {
    return *a+*b;
}

I have written a main program that verifies that int calc_() does indeed return 2 when called as calc_(1,1) in C, but when I run the program I get the output from Fortran.

I am using this makefile # Use gcc for C and gfortran for Fortran code. CC=gcc FC=gfortran

calc : calcf.o calcc.o
    $(FC) -o calc calcf.o calcc.o

calcc.o : calcc.c
    $(CC) -Wall -c calcc.c

calcf.o: calcf.f90
    $(FC) -c calcf.f90

I cannot for the world figure out why this is the case, and it's driving me mad.


回答1:


Almost embarrassingly simple. You must declare calc as an integer in Fortran. The working Fortran code is thus

program calculator
    !implicit none

    ! type declaration statements
    integer x, calc
    x = 1

    ! executable statements
    x = calc(1,1)
    print *, x

end program calculator


来源:https://stackoverflow.com/questions/37888128/write-c-function-that-returns-int-to-fortran

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!