1

I was reading this SO question: Linking fortran and c++ binaries using gcc.

Could someone explain if it is possible do similar stuff with fortran 77 with C++?
I need to extract some subroutines from fortran 77 files and turn them into a C++ dll. The newly created dll will need to work with old fortran 77 files.

Some step-by-step explanations on how to link & compile fortran 77 file with c++ dll would be great. I have searched a lot and am a novice with mixed programming.

Community
  • 1
  • 1

2 Answers2

0

Linking C++ into a Fortran program is next to impossible because of the name mangling unless everything lives inside an extern "C". Alternatively, you could make the interface extern "C" and the implementation C++.

This is how to link an existing Fortran library with a C++ program which is what the other article is about.

1) Create a Fortran subprogram, say worker.for. This is F77 so remember the 6 leading spaces

      subroutine printhi
      print *, 'it works'
      end subroutine

2) Create a C++ program that calls it, say boss.cpp. Note trailing underscore in the Fortran routine name

#include <iostream>
// Avoid any name mangling
extern "C"
{
extern void __attribute__((stdcall)) printhi_(void);
}

int main()
{
   std::cout << "Calling fortran" << std::endl;
   printhi_();
   std::cout << "Returned to C++" << std::endl;
}

3) Build the F77 routine

gfortran -c worker.for

4) Build and link the C++ program. Add the fortran library to resolve any fortran specific bits.

g++ boss.cpp worker.o -o cboss -L/usr/lib -lgfortran

5) Run the program

./a.out
cup
  • 7,589
  • 4
  • 19
  • 42
0

This one is for a fortran program calling C++. Note that the interfaces must be in an extern "C" otherwise the linker won't find them.

1) Create a C routine called worker.cpp. Note the trailing underscore after the routine name.

#include <iostream>
extern "C"
{
extern void __attribute__((stdcall)) worker_()
{
   std::cout << "Hey it works" << std::endl;
}
}

2) Create a Fortran program called boss.for. Note that there is no trailing underscore when you call the C routine.

      program main
      external worker
      print *, 'Calling C'
      call worker
      print *, 'Back to F77'
      stop
      end

3) Compile the C code

g++ -c worker.cpp

4) Compile and link the Fortran code

gfortran boss.for worker.o -o fboss -L/usr/lib -lstdc++
cup
  • 7,589
  • 4
  • 19
  • 42