我真的需要你的帮助!我的工作期限很短,我想学习的足够知识来完成一些工作。到目前为止,我已经处理了一个似乎很简单的问题,但是我还没有能够成功地在线实现解决方案,这已经过去了一周。
长话短说:我需要从F77调用C ++代码。我正在使用g ++和gfortran进行编译。我是makefile的完整书呆子。当这些代码作为各自程序的一部分进行编译时,它们没有错误(我从我的C ++代码中获取一个函数,而不是main(),并尝试将其与fortran代码一起使用)。这是我得到的:
C ++代码:
#include <cmath>
#include <vector>
using namespace std;
extern"C" double ShtObFun(double x[], int &tp)
{
return //double precision awesomeness
}
Fortran代码:
subroutine objfun(nv, var, f, impass)
implicit real(8) (a-h,o-z), integer (i-n)
c initializations including tp, used below
f = ShtObFun(var, tp)
return
end
Makefile(仅显示上面列出的文件):
all:
g++ -c Objective_Functions.cpp
gfortran -c -O3 opcase1.f
gfortran opcase1.o Objective_Functions.o -fbounds-check -lstdc++ -g -o Program.out
rm *.o
错误:
opcase1.o: In function 'objfun_':
opcase1.f:(.text+0xbd): undefined reference to 'shtobfun_'
collect2: ld returned 1 exit status
我已经尝试了多种其他方法,但它们没有起作用。如果需要,我可以稍后列出。有人在这里看到这个问题吗?
我检查过的网站:
calling C++ function from fortran not C,
Linking fortran and c++ binaries using gcc,,Calling C Code from FORTRAN,Cookbook - Calling C from Fortran,YoLinux - Using C/C++ and Fortran together
编辑(响应第一个答案):
如果我将C ++代码重写为:
#include <cmath>
#include <vector>
using namespace std;
double ShtObFun(double x[], int &tp)
extern"C" double shtobfun_(double *x, int *tp) {
return ShtObFun(x, *tp);
}
{
cout << "reached tp = " << tp << endl;
exit(1);
}
我收到此错误:
错误:“外部”之前的预期初始化
错误:“ {”令牌之前的预期unqualified-id
如果我将C ++代码重写为:
#include <cmath>
#include <vector>
using namespace std;
double ShtObFun(double x[], int &tp);
extern"C" double shtobfun_(double *x, int *tp) {
return ShtObFun(x, *tp);
}
double ShtObFun(double x[], int &tp)
{
cout << "reached tp = " << tp << endl;
exit(1);
}
代码将编译,但是我得到的结果是“ reached tp = 0”,而它应该说“ reached tp = 1”,因为我在fortran代码中将tp初始化为1(整数tp = 1)。如果我简单地将该函数声明为:
extern"C" double shtobfun_(double *x, int *tp)
{
//cout, etc
}
最佳答案
声明或别名
extern"C" double ShtObFun(double x[], int &tp)
如
extern"C" double shtobfun_(double x[], int &tp)
见http://gcc.gnu.org/onlinedocs/gcc/Weak-Pragmas.html
那是您的第一步。第二步是认识到Fortran不了解引用,而且它会将所有参数作为指针传递。因此您的F77接口应声明为:
extern"C" double shtobfun_(double x[], int *tp);
放在一起:
double ShtObFun(double x[], int &tp)
extern"C" double shtobfun_(double *x, int *tp) {
return ShtObFun(x, *tp);
}
关于c++ - 从Fortran调用C++(链接问题?),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37141025/