我在编译为我的研究提供的一段代码时遇到了问题。它由一个用 C++ 编写的组件和另一个用 FORTRAN 编写的组件组成。我认为问题与我的 gcc 版本有关。
例如,第一个文件是一个 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自版本 4.5.x 以来,gfortran 处理“main”和“MAIN__”函数命名的方式发生了变化,但我不确定如何解决我的问题。
关于我缺少什么有什么想法吗?感谢您的帮助!
最佳答案
您有两个主要
符号:
int main(){
cout << "main in C++\n";
return MAIN__();
}
和
program test
implicit none
print*, 'MAIN in FORTRAN'
end program test
主程序
的符号为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 原型(prototype)相匹配。
关于gcc - gfortran main 的多重定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33594960/