use*_*626 5 c++ linker fortran fortran-iso-c-binding intel-fortran
我在网上做了一些搜索,但我找不到如何从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;
}
Run Code Online (Sandbox Code Playgroud)
我的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
Run Code Online (Sandbox Code Playgroud)
我ifort
用来编译我的Fortran代码和g ++ for C++代码.我试过这个终端命令:
$ ifort -c Program.f90
$ g++ -o Main.cpp Program.o
Run Code Online (Sandbox Code Playgroud)
但我得到的错误是"链接器输入文件未使用,因为链接没有完成." 我不知道如何将两者联系在一起.如果有人能帮助我,我会非常感激!
PS - 我已经尝试-lg2c
在编译行的末尾添加,但它无法识别.
这里几乎没有问题,不允许对象的名称匹配.首先,在C++代码中指定外部函数具有C签名:
在test.cpp中:
extern "C" int Add( int *, int * );
extern "C" int Multiply( int *, int * );
Run Code Online (Sandbox Code Playgroud)
请参阅在C++源代码中,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
Run Code Online (Sandbox Code Playgroud)
编译(不介意我使用英特尔套件,我的g ++和gfortran非常老):
$ ifort -c test_f.f90
$ icpc -c test.cpp
Run Code Online (Sandbox Code Playgroud)
链接:
$ icpc test_f.o test.o
Run Code Online (Sandbox Code Playgroud)
执行a.out
现在应该按预期工作.