gfortran main的多个定义 [英] gfortran multiple definition of main
问题描述
我在编写一段研究代码时遇到了麻烦.它由一个用C ++编写的组件和另一个用FORTRAN编写的组件组成.我认为问题与我的gcc版本有关.
I'm having trouble with compiling a piece of code I have been given for my research. It consists of one component written in C++ and the other in FORTRAN. I think the problem is to do with my gcc version.
例如,第一个文件是C ++文件(foo.ccp)
The first file for example is a C++ file (foo.ccp)
#include <iostream>
using namespace std;
extern "C" {
extern int MAIN__();
}
int main(){
cout << "main in C++\n";
return MAIN__();
}
第二个是bar.f90:
The second is bar.f90:
program test
implicit none
print*, 'MAIN in FORTRAN'
end program test
我正在尝试像这样编译它:
I'm trying to compile it like so:
g++ -c foo.cpp
gfortran foo.o -lstdc++ bar.f90
它可以在GCC-4.4.7上正常编译,但在GCC-4.8.x上却可以读取以下错误:
It compiles fine with GCC-4.4.7 but fails with GCC-4.8.x with the error reading:
/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
我已阅读此处,其中发生了变化从版本4.5.x开始,gfortran如何处理'main'和'MAIN__'函数的命名,但是我不确定如何解决我的问题.
I've read here that there's a change in how gfortran handles naming of the 'main' and 'MAIN__' functions since version 4.5.x but I'm not sure how to fix my problem.
关于我所缺少的东西有什么想法吗?感谢您的帮助!
Any ideas as to what I'm missing? Thanks for your help!
推荐答案
您有两个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,您应该这样做:
The main program
is given the symbol main
. You cannot link these two programs together because the two main
symbols conflict. You also have the issue that since the Fortran program
is given the main
symbol and not MAIN__
that symbol is undefined. Your goal is to call Fortran from C++, you should do this:
#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原型匹配.
These will compile and link together and do what your code is attempting to do. These make use of Fortran's iso_c_binding
features to ensure the Fortran function is fully interoperable with C with proper case and no underscoring funny business. The Fortran function also returns a value so matches the C prototype your have provided in your example.
这篇关于gfortran main的多个定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!