加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 10:24:59 所属栏目:百科 来源:网络整理
导读:我真的需要你的帮助!我正处于截止日期,我正在努力学习,以完成一些工作.现在已经有一周多了,我正在处理看似简单的问题,但我无法在线成功实施解决方案. 长话短说:我需要从F77调用C代码.我正在用g和gfortran编译.我是一个完整的新手来制作文件.当这些代码被编
我真的需要你的帮助!我正处于截止日期,我正在努力学习,以完成一些工作.现在已经有一周多了,我正在处理看似简单的问题,但我无法在线成功实施解决方案.

长话短说:我需要从F77调用C代码.我正在用g和gfortran编译.我是一个完整的新手来制作文件.当这些代码被编译为各自程序的一部分时,它们没有错误(我从我的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);
}

我收到此错误:
????错误:’extern’之前的预期初始值设定项
????错误:在'{‘标记之前预期的unqualified-id

如果我重写C代码为:

#include <cmath>
#include <vector>
using namespace std;

double ShtObFun(double x[],int &tp);

extern"C" double shtobfun_(double *x,*tp);
}

double ShtObFun(double x[],int &tp)
{
    cout << "reached tp = " << tp << endl;
    exit(1);
}

代码将编译,但我得到的结果是“达到tp = 0”,而它应该说“达到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[],*tp);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读