Undefined reference to Fortran function in C++

2019-07-25 04:06发布

问题:

I can't seem to figure out why this isn't working.

/* main.cpp */
#include <stdio.h>
extern "C"
{
    int __stdcall inhalf(int *);
}
int main()
{
    int toHalf = 2;
    int halved = inhalf(&toHalf);
    printf("Half of 2 is %d", halved);
    return 0;
}

Ok, that looks good.

$ g++ -c main.cpp

No errors.

! functions.f90
function inhalf(i) result(j)
    integer, intent(in) :: i
    integer             :: j
    j = i/2
end function inhalf

I'm pretty sure that's right.

$ gfortran -c functions.f90

So far so good...

$ gcc -o testo main.o functions.o
main.o:main.cpp:(.text+0x24): undefined reference to `inhalf@4'
collect2.exe: error: ld returned 1 exit status

I've been looking this up for over an hour, but I couldn't find anything that worked for this case. How should I solve this?

回答1:

For full C compatibility you can use the bind feature of modern Fortran:

! functions.f90
function inhalf(i) result(j) bind(C,name='inhalf')
    integer, intent(in) :: i
    integer             :: j
    j = i/2
end function inhalf

This allows you to give a name to the function that you can use in C (and others) without relying on the naming scheme your compiler uses on its own.

The __stdcall is Win32 only (and the default behavior for linking, see here). You can safely remove it. [Actually it is required for compiling your code in Linux. ]