在C ++中对Fortran函数的未定义引用 [英] Undefined reference to Fortran function in C++
问题描述
我似乎无法找出为什么这不工作。
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;
}
好,看起来不错。
$ 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
我一直在寻找这个超过一个小时,但我找不到任何工作的情况下。我应该如何解决这个问题?
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?
推荐答案
对于完整的C兼容性你可以使用 bind
现代Fortran的功能:
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
这样可以给函数,您可以在C(和其他人)中使用,而不依赖于编译器自己使用的命名方案。
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.
__ stdcall
仅适用于Win32(以及链接的默认行为,请参阅在这里)。您可以安全地删除它。 [实际上,在Linux中编译代码是必需的。 ]
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. ]
这篇关于在C ++中对Fortran函数的未定义引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!