Calling C++ from Fortran (linking issue?)(从 Fortran 调用 C++(链接问题?))
问题描述
我真的需要你的帮助!我在最后期限内,我正在努力学习足以完成一些工作.一个多星期以来,我正在处理一个看似简单的问题,但我无法成功地在线实施解决方案.
I really need your help! I'm on a deadline and I'm trying to learn just enough to get some work done. It's been well over a week now that I'm dealing with what appears to be a straightforward issue but I haven't been able to successfully implement solutions online.
长话短说:我需要从 F77 调用 C++ 代码.我正在用 g++ 和 gfortran 编译.我是makefile的新手.当这些代码被编译为它们各自程序的一部分时,它们没有错误(我从我的 C++ 代码中获取一个函数,而不是 main(),并尝试将它与 fortran 代码一起使用).这是我得到的:
Long story short: I need to call C++ code from F77. I'm compiling with g++ and gfortran. I'm a complete newb to makefiles. When these codes are compiled as part of their respective programs, they are bug free (I'm taking a function from my C++ code, not main(), and trying to use it with the fortran code). Here's what I've got:
C++ 代码:
Fortran 代码:
Makefile(仅显示上面列出的文件):
错误:
我已经尝试了多种其他方法,但都没有奏效.如果需要,我可以稍后列出.有人看到这里的问题吗?
I have tried this a variety of other ways and they did not work. I can list those later if requested. Does anyone see the issue here?
我检查过的网站:
从 fortran 而非 C 调用 C++ 函数,使用 gcc 链接 fortran 和 c++ 二进制文件, , 从 FORTRAN 调用 C 代码, Cookbook - 从 Fortran 调用 C, YoLinux - 将 C/C++ 和 Fortran 结合使用
编辑(回复第一个答案):
如果我将 C++ 代码重写为:
If I rewrite C++ code as:
我收到此错误:错误:extern"之前的预期初始化程序错误:{"令牌之前的预期 unqualified-id
I get this error: error: expected initializer before 'extern' error: expected unqualified-id before '{' token
如果我将 C++ 代码重写为:
If I rewrite C++ code as:
代码将编译,但我得到的结果是达到 tp = 0",而它应该说达到 tp = 1",因为我在 fortran 代码中将 tp 初始化为 1(整数 tp = 1).如果我简单地将函数声明为:
The code will compile but the result I get is "reached tp = 0", while it should say "reached tp = 1" because I initialized tp to 1 in the fortran code (integer tp = 1). And I get the same issue if I simply declare the function as:
推荐答案
声明或别名
作为
参见 http://gcc.gnu.org/onlinedocs/gcc/Weak-Pragmas.html
这是你的第一步.第二步是认识到 Fortran 不知道引用,而且它将所有参数作为指针传递.所以你的 F77 接口应该声明为:
That's you first step. Second step is to recognize that Fortran has no idea about references, moreover it passes all arguments as a pointer. so you F77 interface should be declared as:
把它们放在一起:
这篇关于从 Fortran 调用 C++(链接问题?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!