Mixed programming: Calling FORTRAN from C

501 views Asked by At

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
2

There are 2 answers

1
Peter Petrik On BEST ANSWER

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);
1
Zeeshan On

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