【问题标题】:Undefined reference to Fortran function in C++C++ 中对 Fortran 函数的未定义引用
【发布时间】:2016-06-14 10:10:00
【问题描述】:

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

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

我已经查找了一个多小时,但找不到任何适用于此案例的内容。我该如何解决这个问题?

【问题讨论】:

  • inhalf 在 fortran 中将被称为 inhalf_ 在 c 中。
  • inhalf@4 表示,inhalf() 的函数声明仍然涉及一些不需要的修改。
  • 对 Fortran 问题使用标签 fortran。在需要区分的地方添加特定版本。
  • 有一个完整的标签是关于接口 C 和 Fortran fortran-iso-c-binding
  • @BoBTFish 不一定。编译器可能会选择其他名称作为函数名。您甚至可以在大多数 Fortran 编译器中禁用下划线。

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


【解决方案1】:

为了完全兼容 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 中编译代码是必需的。 ]

【讨论】:

  • 我猜stdcall问题仍然存在。
  • @VladimirF 标准调用问题?我试过了,它奏效了。
  • @robbie0630 你的__stdcall 可能会在 32 位窗口上导致各种问题。注意inhalf@4 中的 @4
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-03
  • 1970-01-01
  • 1970-01-01
  • 2011-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多