[英]Read C++ 'Hello World' from Fortran
我正在嘗試驗證一個簡單的hello world函數用c ++編寫的函數可以從FORTRAN腳本中調用(gfortran 4.9.20。我對c ++和FORTRAN都沒什么經驗,所以我認為這是我應該開始的。
//code.cpp
#include <iostream>
extern "C"
{
void worker();
int main()
{
worker();
}
void worker()
{
std::cout << "Hello, World!\n";
}
}
和標題如下
//code.h
#include "code.cpp"
extern "C"
{
void worker();
}
我可以使用下面的簡單代碼在c ++中調用我的hello函數
//readheader.cpp
#include "code.h"
extern "C"
{
void worker();
}
我認為一切都很順利,直到我嘗試使用FORTRAN讀取相同的代碼。 它可能是我的編譯行,此時我不確定我的代碼的哪一部分被破壞了。 以下是我的FORTRAN代碼
c codeF.f
program main
include 'code.h'
print *, 'Calling C'
call worker()
print *, 'Back to F77'
end program main
我的編譯腳本
gfortran -I/Path/to/file -c codeF.f
我在'code.h'標題中得到8個錯誤。 雖然我的c ++代碼可以讀取標題FORTRAN不能。 到目前為止,我所有的互聯網研究都引導我到這里,希望有經驗的人可以幫助我。
謝謝
您不能在Fortran中包含C ++標頭。 您必須創建一個描述該過程的接口塊 ,以便Fortran可以調用它:
program main
interface
subroutine worker() bind(C,name="worker")
end subroutine
end interface
print *, 'Calling C'
call worker()
print *, 'Back to F2003'
end program main
您可能仍然遇到問題,不建議將Fortran和C ++ I / O( std:cout
流和print
語句)合並到一個可執行文件中。 它們不能保證兼容,並且可能發生奇怪的事情。
忘了FORTRAN 77,它已經40歲了,這比這里的很多人(包括我)都要多。 考慮到計算機和程序的發展速度,即使Fortran 90也太老了。 最新標准是Fortran 2008,Fortran 2015作為草案存在。
有關將C和C ++與Fortran連接的更多信息,請參閱fortran-iso-c-binding中的問題和解答。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.