Mixed programming: Calling FORTRAN from C

南楼画角 提交于 2019-12-11 11:43:00

问题


I have to do a proof of concept on calling FORTRAN subroutines from C/C++. I don't know what I am in right direction, please guide me....

What I did is...

I wrote the following FORTRAN code

INTEGER*4 FUNCTION Fact (n)
INTEGER*4 n
INTEGER*4 i, amt
amt = 1
DO i = 1, n
amt = amt * i
END DO
Fact = amt
END

SUBROUTINE Pythagoras (a, b, c)
REAL*4 a
REAL*4 b
REAL*4 c 
c = SQRT (a * a + b * b)
END

compiled it using g77 as g77.exe -c FORTRANfun.for

I wrote following c code...

#include <stdio.h>

extern int __stdcall FACT (int n);
extern void __stdcall PYTHAGORAS (float a, float b, float *c);

main()
{
    float c;
    printf("Factorial of 7 is: %d\n", FACT(7));
    PYTHAGORAS (30, 40, &c);
    printf("Hypotenuse if sides 30, 40 is: %f\n", c);
}

compiled it using Visual Studio C compiler as cl /c new.c

When I tried to link, as LINK new.obj FORTRANfun.o I am getting the following error...

new.obj : error LNK2019: unresolved external symbol _FACT@4 referenced in function _main
new.obj : error LNK2019: unresolved external symbol _PYTHAGORAS@12 referenced in function _main
new.exe : fatal error LNK1120: 2 unresolved externals

回答1:


On top of Zeeshan answer, you have to use pointers for passing variables to Fortran:

extern int __stdcall fact(int* n);
extern void __stdcall pythagoras(float* a, float* b, float *c);



回答2:


It's due to symbols case most of the time.

The f77 comiler flags "-fno-underscore" and "-fno-second-underscore" will alter the default naming in the object code and thus affect linking. One may view the object file with the command nm (i.e.: nm file.o).

Note: The case in FORTRAN is NOT preserved and is represented in lower case in the object file. The g77 compiler option "-fsource-case-lower" is default. GNU g77 FORTRAN can be case sensitive with the compile option "-fsource-case-preserve".

Refer THIS



来源:https://stackoverflow.com/questions/23669364/mixed-programming-calling-fortran-from-c

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