2015-11-08 54 views
2

我在編譯我的研究代碼時遇到了麻煩。它由一個用C++編寫的組件和另一個用FORTRAN編寫的組件組成。我認爲問題在於使用我的gcc版本。gfortran主體的多重定義

例如第一個文件是一個C++文件(foo.ccp)

#include <iostream> 
using namespace std; 

extern "C" { 
    extern int MAIN__(); 
} 

int main(){ 
    cout << "main in C++\n"; 
    return MAIN__(); 
} 

第二是bar.f90:

program test 
    implicit none 
    print*, 'MAIN in FORTRAN' 
end program test 

我試圖編譯它像這樣:

g++ -c foo.cpp 
gfortran foo.o -lstdc++ bar.f90 

它編譯罰款與GCC-4.4.7,但未能與GCC-4.8.x與錯誤閱讀:

/tmp/cc5xIAFq.o: In function `main': 
bar.f90:(.text+0x6d): multiple definition of `main' 
foo.o:foo.cpp:(.text+0x0): first defined here 
foo.o: In function `main': 
foo.cpp:(.text+0x14): undefined reference to `MAIN__' 
collect2: error: ld returned 1 exit status 

我讀過here有在我如何gfortran手柄命名的,因爲版本4.5.x「主」和「MAIN__」的功能,但我不知道如何解決我的問題的變化。

任何想法,我失蹤了?謝謝你的幫助!

+1

你只能有1個主。你想去哪裏呢?在fortran或c? – Ross

回答

2

你有兩個main符號:

int main(){ 
    cout << "main in C++\n"; 
    return MAIN__(); 
} 

program test 
    implicit none 
    print*, 'MAIN in FORTRAN' 
end program test 

主要program用符號main。您不能將這兩個程序鏈接在一起,因爲兩個main符號相沖突。您還有一個問題,即Fortran program的符號是main,而不是MAIN__,因此該符號未定義。你的目標是從C++調用Fortran語言,你應該這樣做:

#include <iostream> 

extern "C" { 
    int FortMain(); 
} 

int main() 
{ 
    std::cout << "main in C++\n"; 
    return FortMain(); 
} 

function FortMain() bind(C,name="FortMain") 
    use iso_c_binding 
    implicit none 
    integer(c_int) :: FortMain 
    print *, "FortMain" 
    FortMain = 0 
end function FortMain 

這將編譯和鏈接在一起做什麼,你的代碼是試圖做。這些功能利用Fortran的iso_c_binding功能來確保Fortran功能可與C完全互操作,並且不會出現有趣的業務。 Fortran函數還會返回一個值,以便與您在示例中提供的C原型匹配。

+0

是的,這工作。我建議用一個函數替換我的FORTRAN程序。謝謝! – user2982871