C ++中对Fortran函数的未定义引用

时间:2016-03-01 19:58:18

标签: c++ gcc fortran g++ gfortran

我似乎无法弄清楚为什么这不起作用。

/* 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;
}

好的,看起来不错。

$ g++ -c main.cpp

没有错误。

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

我很确定这是对的。

$ gfortran -c functions.f90

到目前为止一直很好......

$ 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

我已经看了一个多小时了,但我找不到任何适合这种情况的东西。我该怎么解决这个问题?

1 个答案:

答案 0 :(得分:0)

要获得完全C兼容性,您可以使用现代Fortran的bind功能:

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

这允许您为可以在C(和其他)中使用的函数指定名称,而不依赖于编译器自己使用的命名方案。

__stdcall仅限Win32(以及链接的默认行为,请参阅here)。你可以安全地删除它。 [实际上,在Linux中编译代码是必需的。 ]

相关问题