混合C ++和Fortran链接问题

时间:2013-10-09 15:55:19

标签: c++ linker fortran intel-fortran fortran-iso-c-binding

我已经在线搜索了一些但我无法找到如何从linux编译简单的C ++和Fortran代码。我需要让它变得复杂,但我只需要知道如何从一个简单的例子开始。

我的C ++代码是这样的:

#include <iostream>
using namespace std;

extern int Add( int *, int * );
extern int Multiply( int *, int * );

int main()
{
    int a,b,c;  
    cout << "Enter 2 values: ";
    cin >> a >> b;

    c = Add(&a,&b);
    cout << a << " + " << b << " = " << c << endl;
    c = Multiply(&a,&b);
    cout << a << " * " << b << " = " << c << endl;
    return 0;
}

我的Fortran代码就是这样:

integer function Add(a,b)
    integer a,b
    Add = a+b
    return
end


integer function Multiply(a,b)
    integer a,b
    Multiply = a*b
    return
end

我使用ifort编译我的Fortran代码和g ++ for C ++代码。我试过这个终端命令:

$ ifort -c Program.f90
$ g++ -o Main.cpp Program.o

但我得到的错误是“链接器输入文件未使用,因为链接未完成”。 我不知道如何将两者联系在一起。如果有人能帮助我,我会非常感激!

PS - 我尝试在编译行末尾添加-lg2c,但无法识别。

1 个答案:

答案 0 :(得分:8)

这里几乎没有让对象名称匹配的问题。首先,在C ++代码中指定外部函数具有C签名:

在test.cpp中:

extern "C" int Add( int *, int * );
extern "C" int Multiply( int *, int * );

有关详细信息,请参阅In C++ source, what is the effect of extern "C"?

在Fortran代码中,通过在模块中放置过程使接口显式化,并使用iso_c_binding让Fortran对象显示为有效的C对象。请注意,我们可以通过bind关键字明确指定C或C ++程序将看到的对象的名称:

test_f.f90:

module mymod
use iso_c_binding
implicit none

contains

integer(kind=c_int) function Add(a,b) bind(c,name='Add')
    integer(kind=c_int) :: a,b
    Add = a+b
end function

integer(kind=c_int) function Multiply(a,b) bind(c,name='Multiply')
    integer(kind=c_int) :: a,b
    Multiply = a*b
end function

endmodule mymod

编译(不介意我使用英特尔套件,我的g ++和gfortran已经很老了):

$ ifort -c test_f.f90 
$ icpc -c test.cpp 

链接:

$ icpc test_f.o test.o

执行a.out现在应该按预期工作。

相关问题