gfortran multiple definition of main

一世执手 提交于 2019-12-10 17:54:23

问题


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.

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__();
}

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

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

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!


回答1:


You have two main symbols:

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

and

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

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();
}

and

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

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.



来源:https://stackoverflow.com/questions/33594960/gfortran-multiple-definition-of-main

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!