Undefined reference to Fortran function in C++

試著忘記壹切 提交于 2019-12-11 11:34:23

问题


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



来源:https://stackoverflow.com/questions/35732273/undefined-reference-to-fortran-function-in-c

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