c++ - 从 Fortran 调用 C++(链接问题?)

标签 c++ linker makefile fortran

我真的需要你的帮助!我在截止日期前,我正在努力学习足以完成一些工作。一个多星期以来,我一直在处理一个看似简单的问题,但我未能成功地在线实现解决方案。

长话短说:我需要从 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);
}

我得到这个错误: 错误:“外部”之前的预期初始化程序 错误:'{' 标记前应为不合格 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 接口(interface)应该声明为:

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

相关文章:

c++ - C++ 中的简明列表/vector

c++ - 如何使用 boost base64_text (c++) 将 opencv 图像转换为字符串

C++,重新定义运算符=,给矩阵赋一个子矩阵

c++ - 如何使用 Windows x64 记录堆栈帧

iphone - 为什么链接器提示缺少符号?

c++ - 链接到正确的库

linker - 在链接时将多个目标文件中的符号连接到一个表(例如 vtable)中

makefile - 在 make 中根据计算变量创建目标

c++ - 链接对象和静态库

linux - 如何使用预构建的内核输出目录构建 linux 内核模块?