混合 C++ 和 Fortran 链接问题

我在网上做了一些搜索,但我找不到如何从 linux 编译简单的 C++ 和 Fortran 代码.我需要让它变得复杂,但我只需要知道如何从一个简单的例子开始.

I have done some searching online but I cannot find out how to compile a simple C++ and Fortran code from linux. I need to get complex with it, but I just need to know how to start with a simple example.

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

My C++ code is this:

#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 代码是这样的:

My Fortran Code is this:

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 代码和用于 C++ 代码的 g++.我试过这个终端命令:

I am using ifort to compile my Fortran code and g++ for C++ code. I have tried this terminal command:

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

但我收到的错误是链接器输入文件未使用,因为链接未完成".我不确定如何将两者联系在一起.如果有人可以帮助我,我将不胜感激!

But the error I am getting says "linker input file unused because linking not done." I am not sure how to link the two together. If someone could please help me out I would greatly appreciate it!

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

PS - I have tried adding -lg2c at the end of my compilation line, and it is not recognized.

推荐答案

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

There are few issues here that don't let names of the objects match. First, specify in the C++ code that the external functions have the C signature:

在 test.cpp 中:

In test.cpp:

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

参见在C++源码中,效果是什么extern "C"? 了解更多详情.

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

In your Fortran code, make the interface explicit by placing procedures in the module, and use iso_c_binding to let Fortran objects appear as valid C objects. Notice that we can explicitly specify the names of the objects that the C or C++ programs will see through the bind keyword:

test_f.f90:

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 已经很老了):

Compile (don't mind me using the Intel suite, my g++ & gfortran are very old):

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

链接:

$ icpc test_f.o test.o

执行 a.out 现在应该可以按预期工作了.

Executing a.out should now work as expected.

相关文章