[英]Mixed C++ and Fortran Linking Issue
我在網上做了一些搜索,但我找不到如何從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
,但無法識別。
這里幾乎沒有問題,不允許對象的名稱匹配。 首先,在C ++代碼中指定外部函數具有C簽名:
在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 ++程序將看到的對象的名稱:
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
現在應該按預期工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.