3

I'm trying to verify a a simple hello world function written in c++ can be called from a FORTRAN script (gfortran 4.9.20. I have little experience with both c++ and FORTRAN so I thought this is were I should start.

//code.cpp
#include <iostream>

extern "C"
{
  void worker();
  int main()
    {
      worker();
    }
  void worker()
    {
      std::cout << "Hello, World!\n";
    }
}

and a header as follows

//code.h
#include "code.cpp"

extern "C"
  {
    void worker();
  }

I was able to call my hello function in c++ with the simple code below

//readheader.cpp
#include "code.h"

extern "C"
  {
    void worker();
  }

I thought all was well until I attempted to read the same code using FORTRAN. It could be my compile line and at this point I'm not sure which part of my code is broken. Below is my FORTRAN Code

c codeF.f

      program main
      include 'code.h'
      print *, 'Calling C'
      call worker()
      print *, 'Back to F77'

      end program main

my compile script

gfortran -I/Path/to/file -c codeF.f

where I get about 8 errors with the 'code.h' header. Although my c++ code can read the header FORTRAN can not. All my internet research so far has lead me here in hopes someone with experience could help me out.

Thanks

1 Answers1

1

You cannot include a C++ header in Fortran. You must create an interface block which describes the procedure so Fortran can call it:

  program main

    interface
      subroutine worker() bind(C,name="worker")
      end subroutine
    end interface

    print *, 'Calling C'
    call worker()
    print *, 'Back to F2003'

  end program main

You may still have problems, it is not advisable to combine Fortran and C++ I/O (the std:cout stream and the print statement) in one executable. They are not guaranteed to be compatible and weird things can happen.

And forget FORTRAN 77, it is 40 years old, that is more than many people here (including me). Even Fortran 90 is too old considering how quickly computers and programs evolve. The latest standard is Fortran 2008 and Fortran 2015 exists as a draft.

See questions and answers in for much more about interfacing C and C++ with Fortran.

  • I will give this a try and the reason FORTRAN 77 is being used is because an old piece of software called MFIX (used for CFD purposes among other things) is largely written in 77. I did not know FORTRAN well enough to consider f90 in its place. Thanks for the advice. – SneakyPanda 40 Apr 06 '16 at 23:21
  • After playing around a bit I was still not able to get it to work. However I've found a solution were I can call existing libraries into FORTRAN that seem to be working for me. That means I no longer have to create my own libraries and headers and hopefully do not have to come back to this question. Thanks for your response though – SneakyPanda 40 Apr 08 '16 at 19:46