Combining FORTRAN and C++, linking error

為{幸葍}努か 提交于 2021-02-19 05:44:05

问题


I should couple in linux one c++ code with old fortran code, where fortan is the main code. Im not expert in this area and I try to start with simple test, but still I cannot compile it. Maybe I'm stupid, but I cannot find a working example anywhere. I managed to compile fortran and c, when the linking can be done by ifort (need to use intel compiler later with the actual fortran code). But If I've understood right, with c++, the linking must be done by c++ compiler (g++).

So what do I do wrong here:

My FORTRAN test code "ftest.f":


PROGRAM MAIN

  IMPLICIT NONE
  INTEGER I
  write(*,*) "hello fortran1"
  CALL ctest()
  write(*,*) "hello fortran2"

END PROGRAM

And C++ code "ctest.cpp"


#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <iostream>

extern "C" void ctest_();

void ctest_(){
   int i;
 //   std::cout << "hello c \n";
   printf("hello c\n");
}

I try to compile with the following:

ifort -c ftest.f
g++ -c ctest.cpp
g++ -ldl -lm -limf -L -l -lifcore ctest.o ftest.o

And I get an error:

/usr/lib/gcc/x86_64-redhat-linux/4.1.2/../../../../lib64/crt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: ld returned 1 exit status

So what should I do to success with linking this program?


回答1:


Your main (entry) is in Fortran part, so one way to solve it is to to use ifort linker instead of g++ (that would also link ifcore automatically)

ifort ctest.o ftest.o ... -lstdc++



回答2:


So looks like I truested too much on one page telling me that I have to use c++ compiler for linking. Earlier just always something else was wrong when trying to link by ifort.

So using ifort with -lstdc++ is really enough with the current version of my test code. Earlier just something else was wrong.

Thank you very much once again, I wish you all the best for your own projects!



来源:https://stackoverflow.com/questions/21600374/combining-fortran-and-c-linking-error

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